Skip to content

Latest commit

 

History

History
134 lines (98 loc) · 2.42 KB

File metadata and controls

134 lines (98 loc) · 2.42 KB

Documentation

Built-in Directives

include: Template Inheritance & Inclusion

{{ include "template" }}

if / elif / else: Conditional Statements

{{ if condition }}Content{{ elif other }}Content{{ else }}Content{{ endif }}

for: Looping

{{ for item of array_items }}{{= item }}{{ endfor }}
{{ for item of object_items | values }}{{= item }}{{ endfor }}

set: Variable Assignment

{{ set foo = 123 }}
{{ set (a, b) = obj }}
{{ set foo }}Content{{ endset }}

block / super: Block Overriding & Inheritance

Blocks with the same name will automatically overwrite or inherit, and blocks are always rendered where they first appear.

{{ block title }}{{ super }}Default Title{{ endblock }}

macro / caller: Macro Definition & Invocation

{{ macro my_macro(x, y) }}Content{{ caller }}{{ endmacro }}

call: Macro Invocation

{{ call my_macro("foo", "bar") }}Content{{ endcall }}

break / continue: Loop Control

{{ break }}
{{ continue }}

comment: Comments

{{# This is a comment #}}

expression (=): Expression Output

{{= foo | upper }}
{{= a if cond else b }}

Built-in Filters

abs, capitalize, add, ceil, compact, div, entries, even, fallback, first, get, groupby, join, json, keys, last, length, lower, map, max, min, mul, odd, omit, pick, repeat, replace, reverse, safe, slice, sort, split, sub, sum, trim, truncate, unique, upper, urldecode, urlencode, values

Examples

{{= foo | upper }}
{{= list | join(",") }}
{{= obj | keys }}
{{= arr | groupby(key_name) }}

Customization

Custom Directive

class CustomNode extends Traversal {
  readonly type = 'CUSTOM'
  constructor(public readonly loc: Loc) {
    super();
  }
}
render('{{ custom }}', {}, {
  parsers: {
    async *custom(token) {
      yield 'NEXT';
      yield new CustomNode(token.loc);
    },
  },
  compilers: {
    CUSTOM: async (node, compiler) => {
      compiler.pushStr(node.loc, '<CUSTOM/>')
    },
  },
})

Custom Filter

const engine = new Engine({
  filters: {
    my_filter(value) {
      return `Custom: ${value}`
    },
  },
})

Usage in template:

{{= foo | my_filter }}

For more details, refer to the source code in packages/janja/src/filters.ts and packages/janja/src/plugins/.