Saltearse al contenido

@withstudiocms/template-lang

StudioCMS viene con su propio lenguaje de plantillas personalizado que es similar en sintaxis a lenguajes de plantillas populares como Handlebars^ o Liquid^. Este lenguaje de plantillas te permite crear plantillas dinámicas y reutilizables en diferentes partes del panel de control de StudioCMS, como en el sistema de plantillas de correo electrónico, o en plugins personalizados que puedas desarrollar.

@withstudiocms/template-lang es un lenguaje de plantillas simple con TypeScript ESM y licencia MIT para plantillas de correo electrónico HTML, similar a Handlebars pero enfocado en simplicidad y integración de datos de base de datos.

  • Sintaxis simple {{variable}} para interpolación de variables
  • Soporte para propiedades anidadas con notación de punto ({{user.name}})
  • TypeScript con soporte completo de ESM
  • Modo estricto para manejo de errores
  • Diseñado específicamente para plantillas de correo electrónico y datos de base de datos
  • Cero dependencias

Perfecto para:

  • Plantillas de correo electrónico HTML
  • Generación de contenido dinámico desde datos de base de datos
  • Necesidades de plantillas simples sin lógica compleja
  • Proyectos TypeScript enfocados en ESM

Para aquellos interesados en usar el lenguaje de plantillas de StudioCMS en sus proyectos, puedes instalarlo usando tu gestor de paquetes preferido:

Ventana de terminal
npm i @withstudiocms/template-lang

Similar a otros lenguajes de plantillas, el lenguaje de plantillas de StudioCMS usa dobles llaves {{ }} para denotar variables que deberían ser reemplazadas con datos reales cuando la plantilla es renderizada.

A diferencia de otros lenguajes de plantillas, el lenguaje de plantillas de StudioCMS se enfoca en la simplicidad y no incluye lógica compleja o estructuras de control. Está principalmente diseñado para interpolación de variables simple.

<h1>Hello {{user.firstName}} {{user.lastName}}!</h1>
<p>Your order #{{order.id}} total is ${{order.total}}</p>
<p>Shipping to: {{user.address.street}}, {{user.address.city}}</p>
basic-usage.ts
import
class TemplateEngine

Main template engine class that provides a simple API for template rendering

TemplateEngine
from '@withstudiocms/template-lang';
const
const engine: TemplateEngine
engine
= new
new TemplateEngine(options?: TemplateOptions): TemplateEngine

Main template engine class that provides a simple API for template rendering

TemplateEngine
();
const
const template: "Hello {{name}}! Welcome to {{company.name}}."
template
= "Hello {{name}}! Welcome to {{company.name}}.";
const
const data: {
name: string;
company: {
name: string;
};
}
data
= {
name: string
name
: "John Doe",
company: {
name: string;
}
company
: {
name: string
name
: "Acme Corp"
}
};
const
const result: string
result
=
const engine: TemplateEngine
engine
.
TemplateEngine.render(template: string, data: TemplateData): string

Render a template string with data

@paramtemplate The template string containing {{variable}} placeholders

@paramdata The data context for variable replacement

@returnsThe rendered template string

render
(
const template: "Hello {{name}}! Welcome to {{company.name}}."
template
,
const data: {
name: string;
company: {
name: string;
};
}
data
);
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const result: string
result
); // "Hello John Doe! Welcome to Acme Corp."
email-template.ts
import
class TemplateEngine

Main template engine class that provides a simple API for template rendering

TemplateEngine
from '@withstudiocms/template-lang';
const
const engine: TemplateEngine
engine
= new
new TemplateEngine(options?: TemplateOptions): TemplateEngine

Main template engine class that provides a simple API for template rendering

TemplateEngine
();
const
const emailTemplate: "\n<!DOCTYPE html>\n<html>\n<head>\n <title>{{subject}}</title>\n</head>\n<body>\n <h1>Hello {{user.name}}!</h1>\n <p>Your order #{{order.id}} has been confirmed.</p>\n <p>Total: {{order.total}}</p>\n</body>\n</html>\n"
emailTemplate
= `
<!DOCTYPE html>
<html>
<head>
<title>{{subject}}</title>
</head>
<body>
<h1>Hello {{user.name}}!</h1>
<p>Your order #{{order.id}} has been confirmed.</p>
<p>Total: {{order.total}}</p>
</body>
</html>
`;
const
const data: {
subject: string;
user: {
name: string;
};
order: {
id: string;
total: string;
};
}
data
= {
subject: string
subject
: "Order Confirmation",
user: {
name: string;
}
user
: {
name: string
name
: "John Doe" },
order: {
id: string;
total: string;
}
order
: {
id: string
id
: "12345",
total: string
total
: "99.99" }
};
const
const html: string
html
=
const engine: TemplateEngine
engine
.
TemplateEngine.render(template: string, data: TemplateData): string

Render a template string with data

@paramtemplate The template string containing {{variable}} placeholders

@paramdata The data context for variable replacement

@returnsThe rendered template string

render
(
const emailTemplate: "\n<!DOCTYPE html>\n<html>\n<head>\n <title>{{subject}}</title>\n</head>\n<body>\n <h1>Hello {{user.name}}!</h1>\n <p>Your order #{{order.id}} has been confirmed.</p>\n <p>Total: {{order.total}}</p>\n</body>\n</html>\n"
emailTemplate
,
const data: {
subject: string;
user: {
name: string;
};
order: {
id: string;
total: string;
};
}
data
);
strict-mode.ts
import
class TemplateEngine

Main template engine class that provides a simple API for template rendering

TemplateEngine
from '@withstudiocms/template-lang';
const
const strictEngine: TemplateEngine
strictEngine
= new
new TemplateEngine(options?: TemplateOptions): TemplateEngine

Main template engine class that provides a simple API for template rendering

TemplateEngine
({
TemplateOptions.strict?: boolean

Whether to throw an error when a variable is not found in the data

@defaultfalse

strict
: true });
// Esto lanzará un error si 'missingVar' no está en los datos
try {
const
const result: string
result
=
const strictEngine: TemplateEngine
strictEngine
.
TemplateEngine.render(template: string, data: TemplateData): string

Render a template string with data

@paramtemplate The template string containing {{variable}} placeholders

@paramdata The data context for variable replacement

@returnsThe rendered template string

render
("Hello {{missingVar}}!", {});
} catch (
var error: unknown
error
) {
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
("Variable not found:", (
var error: unknown
error
as
interface Error
Error
).
Error.message: string
message
);
}
default-values.ts
import
class TemplateEngine

Main template engine class that provides a simple API for template rendering

TemplateEngine
from '@withstudiocms/template-lang';
const
const engine: TemplateEngine
engine
= new
new TemplateEngine(options?: TemplateOptions): TemplateEngine

Main template engine class that provides a simple API for template rendering

TemplateEngine
({
TemplateOptions.defaultValue?: string

Default value to use when a variable is not found and strict is false

@default''

defaultValue
: "[NOT SET]" });
const
const result: string
result
=
const engine: TemplateEngine
engine
.
TemplateEngine.render(template: string, data: TemplateData): string

Render a template string with data

@paramtemplate The template string containing {{variable}} placeholders

@paramdata The data context for variable replacement

@returnsThe rendered template string

render
("Hello {{name}}!", {});
// Resultado: "Hello [NOT SET]!"
template-compilation.ts
import
class TemplateEngine

Main template engine class that provides a simple API for template rendering

TemplateEngine
from '@withstudiocms/template-lang';
const
const engine: TemplateEngine
engine
= new
new TemplateEngine(options?: TemplateOptions): TemplateEngine

Main template engine class that provides a simple API for template rendering

TemplateEngine
();
// Compila una vez, usa múltiples veces
const
const compiled: (data: TemplateData) => string
compiled
=
const engine: TemplateEngine
engine
.
TemplateEngine.compile(template: string): (data: TemplateData) => string

Create a template function that can be reused with different data

@paramtemplate The template string

@returnsA function that takes data and returns rendered template

compile
("Hello {{name}}!");
const
const result1: string
result1
=
const compiled: (data: TemplateData) => string
compiled
({
name: string
name
: "Alice" });
const
const result2: string
result2
=
const compiled: (data: TemplateData) => string
compiled
({
name: string
name
: "Bob" });
new TemplateEngine(options?: TemplateOptions)

render(template: string, data: TemplateData): string Renderiza una plantilla con los datos proporcionados.

compile(template: string): (data: TemplateData) => string Compila una plantilla en una función reutilizable.

hasVariables(template: string): boolean Verifica si una plantilla contiene alguna variable.

getVariables(template: string): string[] Retorna un array de todos los nombres de variables en la plantilla.

setOptions(options: Partial<TemplateOptions>): void Actualiza las opciones del motor.

interface TemplateOptions {
strict?: boolean; // Lanza un error si una variable está faltante (default: false)
defaultValue?: string; // Valor por defecto para variables faltantes (default: '')
}