Skip to content

render()

The render() function provides runtime template rendering. Best for development and templates with dynamic content.

Signature

function render(
template: string,
context?: Record<string, any>,
options?: RenderOptions
): Promise<string>

Parameters

ParameterTypeDescription
templatestringTemplate string to render
contextobjectVariables available in template
optionsRenderOptionsOptional configuration

Options

interface RenderOptions {
autoescape?: boolean // HTML escape by default (default: true)
filters?: Record<string, FilterFunction> // Custom filters
globals?: Record<string, any> // Global variables
}

Basic Usage

import { render } from 'binja'
const html = await render('Hello, {{ name }}!', { name: 'World' })
// Output: Hello, World!

With Filters

const html = await render('{{ title|upper|truncatechars:20 }}', {
title: 'Welcome to our amazing website'
})
// Output: WELCOME TO OUR AMAZI...

With Conditionals

const html = await render(`
{% if user.is_admin %}
<span class="badge">Admin</span>
{% else %}
<span class="badge">User</span>
{% endif %}
`, {
user: { is_admin: true }
})

With Loops

const html = await render(`
{% for item in items %}
<li>{{ loop.index }}. {{ item }}</li>
{% empty %}
<li>No items</li>
{% endfor %}
`, {
items: ['Apple', 'Banana', 'Cherry']
})

Custom Filters

const html = await render('{{ price|currency }}',
{ price: 42.5 },
{
filters: {
currency: (value) => `$${value.toFixed(2)}`
}
}
)
// Output: $42.50

Disabling Autoescape

// Not recommended for user input!
const html = await render('{{ html }}',
{ html: '<b>Bold</b>' },
{ autoescape: false }
)
// Output: <b>Bold</b>

Error Handling

try {
const html = await render('{{ invalid syntax }', {})
} catch (error) {
console.error('Template error:', error.message)
}

Performance Note

For production, consider using compile() for static templates (160x faster) or Environment with caching for templates with inheritance.

See Also

  • compile() - AOT compilation for maximum performance
  • Environment - Full-featured template environment