### Running the render-value Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/render-value/README.md
This command executes the render-value example. Ensure you have Rust and Cargo installed.
```bash
$
cargo run
```
--------------------------------
### Run Hello World Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/hello/README.md
This snippet shows the command to run the hello example and its expected output.
```console
$ cargo run
Hello John!
```
--------------------------------
### Running the Autoreload Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/autoreload/README.md
Execute this command in your terminal to start the example application. You can then edit template files to observe live updates.
```console
$ cargo run
```
--------------------------------
### Running the Minimal Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/minimal/README.md
Execute the minimal MiniJinja example using Cargo to see the templating output.
```bash
$ cargo run
1. Hello John!
2. Hello Peter!
```
--------------------------------
### Install and Use minijinja-cli
Source: https://github.com/mitsuhiko/minijinja/blob/main/README.md
Installs the minijinja command-line interface and demonstrates its basic usage for rendering a template with a variable.
```bash
$ curl -sSfL https://github.com/mitsuhiko/minijinja/releases/latest/download/minijinja-cli-installer.sh | sh
$ echo "Hello {{ name }}" | minijinja-cli - -Dname=World
```
--------------------------------
### Install minijinja-cli with Shell Installer
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/README.md
Installs minijinja-cli using a shell script. This method automatically detects your platform and fetches the appropriate binary.
```shell
curl -sSfL https://github.com/mitsuhiko/minijinja/releases/latest/download/minijinja-cli-installer.sh | sh
```
--------------------------------
### Run Example with Different Languages
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/state-temps/README.md
Execute the example with German and English language settings to observe the cached translation behavior.
```console
$ LANG=de cargo run
```
```console
$ LANG=en cargo run
```
--------------------------------
### Run Example with Compile-Time Bundled Templates
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/embedding/README.md
Execute the example with the 'bundled' feature flag enabled to use compile-time bundled templates. This integrates templates directly into the binary.
```console
$ cargo run --features=bundled
```
--------------------------------
### Install minijinja-py
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-py/README.md
Install the minijinja Python package using pip.
```bash
$ pip install minijinja
```
--------------------------------
### Install minijinja-cli with PowerShell Installer (Windows)
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/README.md
Installs minijinja-cli on Windows using a PowerShell script. Ensure your ExecutionPolicy allows script execution.
```powershell
powershell -ExecutionPolicy ByPass -c "irm https://github.com/mitsuhiko/minijinja/releases/latest/download/minijinja-cli-installer.ps1 | iex"
```
--------------------------------
### Run Custom Loader Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/custom-loader/README.md
Execute the custom loader example using Cargo to see the template rendering output.
```console
$ cargo run
header
Hello World!
footer
```
--------------------------------
### String Slicing with Start, Stop, and Step
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Illustrates string slicing using start, stop, and step parameters. All parameters are optional.
```minijinja
"Hello World"[:5]
```
```minijinja
"Hello"[1:-1]
```
```minijinja
"12345"[::2]
```
--------------------------------
### Run the Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/object-ref/README.md
Execute the project using Cargo to see the object reference system in action.
```console
$ cargo run
```
--------------------------------
### List Slicing with Start, Stop, and Step
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Demonstrates slicing lists using start, stop, and step parameters. All parameters are optional.
```minijinja
[start:stop:step]
```
--------------------------------
### Install minijinja-cli with Homebrew
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/README.md
Installs minijinja-cli on macOS or Linux systems that use the Homebrew package manager.
```shell
brew install minijinja-cli
```
--------------------------------
### CLI Usage Examples
Source: https://github.com/mitsuhiko/minijinja/blob/main/AGENTS.md
Demonstrates how to build and run the minijinja-cli, including rendering templates with data files and piping input.
```bash
# Build and run CLI
cd minijinja-cli
cargo run -- template.j2 data.json
```
```bash
# Example usage
cargo run -- examples/hello.j2 examples/hello.json
```
```bash
echo "Hello {{ name }}" | cargo run -- - -Dname=World
```
--------------------------------
### Install minijinja-cli with Cargo
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/README.md
Compiles and installs the minijinja-cli tool directly from source using the Rust package manager, Cargo.
```shell
cargo install minijinja-cli
```
--------------------------------
### Command-line execution and output
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/render-template/README.md
Shows how to run the example from the command line with specified JSON and template files, and displays the resulting rendered HTML output.
```console
$ cargo run -- -c users.json -t users.html
User List
```
--------------------------------
### Install cargo-fuzz
Source: https://github.com/mitsuhiko/minijinja/blob/main/fuzz/README.md
Installs the cargo-fuzz tool, which is required for running the fuzzers.
```bash
$ cargo install cargo-fuzz
```
--------------------------------
### List Literal Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Demonstrates the creation of list literals in MiniJinja.
```text
['list', 'of', 'objects']
```
--------------------------------
### Example of Line Comments in Minijinja Template
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/lexer-inputs/line-comment.txt
Demonstrates how line comments are used within a Minijinja template. Comments starting with '##' are ignored during rendering.
```html
## this is a comment
## that shall disappear entirely
# for item in seq
- {{ item }}
## this is another line comment
# endfor
## trailing comment
```
--------------------------------
### Basic AutoReloader Setup
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-autoreload/README.md
Demonstrates how to set up an AutoReloader with a specified template path. The notifier is used to watch the directory for changes.
```rust
use minijinja_autoreload::AutoReloader;
use minijinja::{path_loader, Environment};
let reloader = AutoReloader::new(|notifier| {
let mut env = Environment::new();
let template_path = "path/to/templates";
notifier.watch_path(template_path, true);
env.set_loader(path_loader(template_path));
Ok(env)
});
let env = reloader.acquire_env()?;
let tmpl = env.get_template("index.html")?;
```
--------------------------------
### Build and Run MiniJinja CLI
Source: https://github.com/mitsuhiko/minijinja/blob/main/CLAUDE.md
Steps to build and execute the MiniJinja command-line interface, including examples of rendering templates with data files or piped input.
```bash
# Build and run CLI
cd minijinja-cli
cargo run -- template.j2 data.json
# Example usage
cargo run -- examples/hello.j2 examples/hello.json
echo "Hello {{ name }}" | cargo run -- - -Dname=World
```
--------------------------------
### String Literal Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Demonstrates how to define string literals in MiniJinja.
```text
"Hello World"
```
--------------------------------
### C Example: Render a Template
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cabi/README.md
A basic C program demonstrating how to use the minijinja C API. It initializes an environment, adds a template, sets context variables, renders the template, and prints the output.
```c
#include
#include
int main()
{
mj_env *env = mj_env_new();
bool ok = mj_env_add_template(env, "hello", "Hello {{ name }}!");
mj_value ctx = mj_value_new_object();
mj_value_set_string_key(&ctx, "name", mj_value_new_string("C-Lang"));
char *rv = mj_env_render_template(env, "hello", ctx);
if (!rv) {
mj_err_print();
} else {
printf("%s\n", rv);
mj_str_free(rv);
}
mj_env_free(env);
return 0;
}
```
--------------------------------
### Map Literal Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Shows how to define map (dictionary) literals.
```text
{'map': 'of', 'key': 'and', 'value': 'pairs'}
```
--------------------------------
### Template using line statements and comments
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
An example template demonstrating the use of line statements and comments with custom prefixes.
```jinja
## This block is
## completely removed
# for item in [1, 2]
## this is a comment that is also removed including leading whitespace
- {{ item }}
# endfor
```
--------------------------------
### Floating Point Literal Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Illustrates the syntax for floating-point number literals.
```text
42.0
```
--------------------------------
### Addition Expression
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Example of using the addition operator.
```html
{{ 1 + 1 }}
```
--------------------------------
### Callable Invocation Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Demonstrates calling a callable function within a template.
```html
{{ super() }}
```
--------------------------------
### Include and Call Macro from External File
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/macro_include.txt
Includes 'example_macro.txt' and calls the 'example' macro with different argument counts. The `{%- include ... %}` syntax suppresses leading whitespace.
```jinja
{%-
include "example_macro.txt"
%}
{%- set d = "should never show up" %}
{{ example(1, 2, 3) }}
{{ example(1, 2) }}
```
--------------------------------
### Exponentiation Expression
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Example of using the exponentiation operator.
```html
{{ 2**3 }}
```
--------------------------------
### Template Inheritance Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-go/README.md
Illustrates template inheritance using 'extends', 'block', and 'super()' for creating reusable layouts. Ensure 'base.html' and 'child.html' are accessible to the template loader.
```jinja
{# base.html #}
{% block title %}Default{% endblock %}
{% block content %}{% endblock %}
```
```jinja
{# child.html #}
{% extends "base.html" %}
{% block title %}My Page{% endblock %}
{% block content %}
Welcome!
This is my page content.
{% endblock %}
```
```jinja
{% block content %}
{{ super() }}
Additional content
{% endblock %}
```
--------------------------------
### Custom Template Loading in Go
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-go/README.md
Configures the MiniJinja environment to load templates from the filesystem. This example assumes templates are stored in a 'templates' directory. Ensure the 'templates' directory exists and contains the requested template file.
```go
env := minijinja.NewEnvironment()
env.SetLoader(func(name string) (string, error) {
content, err := os.ReadFile(filepath.Join("templates", name))
if err != nil {
return "", err
}
return string(content), nil
})
tmpl, err := env.GetTemplate("index.html")
```
--------------------------------
### Modulo Expression
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Example of using the modulo operator.
```html
{{ 11 % 7 }}
```
--------------------------------
### Boolean and None Literals
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Examples of boolean and the special 'none' literal.
```text
true
```
```text
false
```
```text
none
```
--------------------------------
### List Slicing: From Start
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/slicing.txt
Extracts a sublist from the beginning of the list to the end.
```minijinja
{{ intrange[1:] }}
```
--------------------------------
### Template Inheritance Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/block_scope_extends.txt
This snippet shows a base template and an extending template to illustrate block scope and variable inheritance.
```jinja
{% extends template %}
{% block item_block %}[{{ item }}]{% endblock %}
```
--------------------------------
### Filter Application Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Shows how to apply a filter to an expression using the pipe operator.
```html
{{ name|title }}
```
--------------------------------
### Rendered HTML from line statement example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
The resulting HTML output after processing the template with line statements and comments.
```html
```
--------------------------------
### String Concatenation Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Illustrates using the tilde operator to concatenate strings.
```html
{{ "Hello " ~ name ~ "!" }}
```
--------------------------------
### Division Expression
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Example of using the division operator.
```html
{{ 1 / 2 }}
```
--------------------------------
### String Slicing: From Start
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/slicing.txt
Extracts a substring from the beginning of the string to the end.
```minijinja
{{ hello[1:] }}
```
--------------------------------
### Integer Division Expression
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Example of using the integer division operator.
```html
{{ 5 // 3 }}
```
--------------------------------
### Integer Literal Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Shows various ways to represent integer literals, including binary, octal, and hexadecimal.
```text
42
```
--------------------------------
### Test Operator Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Shows how to use the 'is' operator to perform a test on a value.
```html
{{ name is defined }}
```
--------------------------------
### Containment Operator Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Demonstrates using the 'in' operator to check for membership.
```html
{{ 'apple' in fruits }}
```
--------------------------------
### Raw Tag with Whitespace Control
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/lexer-inputs/raw.txt
Control whitespace around the `raw` tag using hyphens. This example shows trimming whitespace from the start and end of the raw block.
```jinja
{%- raw %} this is a {{ raw }} {% block %} {% endraw -%} after
```
--------------------------------
### Example Jinja Template Syntax
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-go/README.md
A basic Jinja template demonstrating template inheritance and variable interpolation. This template expects a 'name' variable to be provided during rendering.
```jinja
{% extends "layout.html" %}
{% block body %}
Hello {{ name }}!
{% endblock %}
```
--------------------------------
### Run Linting with Clippy
Source: https://github.com/mitsuhiko/minijinja/blob/main/CONTRIBUTING.md
Lint the codebase using Clippy via the Makefile. This command ensures Clippy is installed and runs the linter with specific configurations.
```sh
make lint
```
--------------------------------
### Negated Test Operator Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Shows how to use the 'is not' operator to perform a negated test.
```html
{{ name is not defined }}
```
--------------------------------
### Basic Template Rendering in Go
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-go/README.md
Demonstrates how to create a MiniJinja environment, load a template, and render it with variables. Ensure the template file exists or is added to the environment.
```go
package main
import (
"fmt"
"log"
minijinja "github.com/mitsuhiko/minijinja/minijinja-go/v2"
)
func main() {
env := minijinja.NewEnvironment()
env.AddTemplate("hello.txt", "Hello {{ name }}!")
tmpl, err := env.GetTemplate("hello.txt")
if err != nil {
log.Fatal(err)
}
result, err := tmpl.Render(map[string]any{"name": "World"})
if err != nil {
log.Fatal(err)
}
fmt.Println(result) // Output: Hello World!
}
```
--------------------------------
### Template with custom delimiters
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
An example of a MiniJinja template using custom block and variable delimiters as configured in Rust.
```jinja
\begin{itemize}
\BLOCK{for item in sequence}
\item \VAR{item}
\BLOCK{endfor}
\end{itemize}
```
--------------------------------
### Macro Variable Capture Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/macro_closure_behavior.txt
Shows how macros capture variables based on their definition scope. Variables defined before and after a macro are accessed differently.
```jinja
{% macro before_closure() %}{{ closure }}{% endmacro %}
{% set closure = 1 %}
{% macro after_closure() %}{{ closure }}{% endmacro %}
{% set closure = 2 %}
{% macro after_closure_reset() %}{{ closure }}{% endmacro %}
{{ before_closure() }}
{{ after_closure() }}
{{ after_closure_reset() }}
```
--------------------------------
### MiniJinja REPL Usage
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/README.md
Starts the MiniJinja Read-Eval-Print Loop (REPL) for interactive expression evaluation. Type .help for commands.
```bash
minijinja-cli --repl -D name=World
MiniJinja Expression REPL
Type .help for help. Use .quit or ^D to exit.
>>> name|upper
"WORLD"
>>> range(3)
[0, 1, 2]
```
--------------------------------
### Initialize Environment with Templates
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-py/README.md
Create a MiniJinja Environment by providing a dictionary of template names and their source code.
```python
from minijinja import Environment
env = Environment(templates={
"template_name": "Template source"
})
```
--------------------------------
### List Slicing: Negative Start Reverse
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/slicing.txt
Extracts elements in reverse order starting from the fifth element from the end.
```minijinja
{{ intrange[-5::-1] }}
```
--------------------------------
### Console Output of Dynamic Object Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/dynamic-objects/README.md
The console output shows the rendered HTML from the Jinja template, demonstrating the dynamic class generation applied to the list items and the unordered list.
```console
$ cargo run
```
--------------------------------
### Importing with Context
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/imports.txt
Import macros and include context.
```minijinja
{% from "foo.html" import a as b, b as c with context %}
```
--------------------------------
### Block Scope and Super() Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/block_scope_super.txt
Shows how a variable set within a block is local and how super() accesses the parent block. The 'var' set in the block is local and does not affect the outer scope, while super() renders the content from the parent template.
```html
{% extends "var_setting_layout.txt" %}
{% block test %}before: {% set var = "from self" %}{{ var }}
{{ super() }}
after: {{ var }}{% endblock %}
```
--------------------------------
### Automatic HTML Escaping Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-go/README.md
Illustrates MiniJinja's automatic HTML escaping for templates with .html extensions. Content containing script tags will be escaped to prevent XSS attacks.
```go
env := minijinja.NewEnvironment()
tmpl, _ := env.TemplateFromNamedString("page.html", "{{ content }}")
result, _ := tmpl.Render(map[string]any{
"content": "",
})
```
--------------------------------
### lstrip_blocks and raw directive example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/lexer-inputs/lstrip-blocks-raw.txt
Demonstrates the use of `lstrip_blocks` and `raw` directives in minijinja. The `lstrip_blocks` setting is true, and the `raw` directive prevents Jinja2 from processing the content within it.
```jinja
{
"lstrip_blocks": true,
"trim_blocks": true
}
---
{% raw %}
- {{ item }}
{% endraw %}
```
--------------------------------
### Multiplication Expression
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Example of using the multiplication operator.
```html
{{ 2 * 2 }}
```
--------------------------------
### Render Template from Rust
Source: https://github.com/mitsuhiko/minijinja/blob/main/README.md
Demonstrates how to set up a MiniJinja environment, load a template, and render it with context variables in Rust.
```rust
use minijinja::{Environment, context};
fn main() {
let mut env = Environment::new();
env.add_template("hello.txt", "Hello {{ name }}!").unwrap();
let template = env.get_template("hello.txt").unwrap();
println!("{}", template.render(context! { name => "World" }).unwrap());
}
```
--------------------------------
### Basic Include
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/include.txt
Includes the content of 'foo.txt' into the current template.
```jinja
{% include "foo.txt" %}
```
--------------------------------
### Subtraction Expression
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Example of using the subtraction operator.
```html
{{ 3 - 2 }}
```
--------------------------------
### Positional and Keyword Arguments in Function Calls
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Demonstrates how to call functions with both positional and keyword arguments, where keyword arguments are equivalent to dictionary syntax.
```minijinja
foo(a=1, b=2)
```
--------------------------------
### Calling Built-in Functions
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/call.txt
Demonstrates calling built-in functions like super() and loop.cycle() with arguments.
```minijinja
{{ super() }}
{{ loop.cycle(1, 2) }}
```
--------------------------------
### Configure Custom Syntax Delimiters (Old)
Source: https://github.com/mitsuhiko/minijinja/blob/main/UPDATING.md
Demonstrates the previous method for setting custom syntax delimiters in MiniJinja 1.x.
```rust
use minijinja::{Environment, Syntax};
let mut env = Environment::new();
env.set_syntax(minijinja::Syntax {
block_start: "{".into(),
block_end: "}".into(),
variable_start: "$".into(),
variable_end: "}".into(),
comment_start: "{*"..into(),
comment_end: "*}"..into(),
})
.unwrap();
```
--------------------------------
### Importing Template with Context
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/imports.txt
Import an entire template file and include context.
```minijinja
{% import "foo.html" as x with context %}
```
--------------------------------
### NOT Logic Operator
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Example of using the 'not' operator to negate a boolean expression.
```html
{{ not true }}
```
--------------------------------
### OR Logic Operator
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Example of using the 'or' operator to combine boolean expressions.
```html
{{ true or false }}
```
--------------------------------
### Define and Use a Macro
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-go/examples/macros/macros.html
Demonstrates defining a macro named 'render_input' that takes 'name', 'value', and an optional 'type' argument. It also shows how to create an alias for a macro.
```html
{% macro render_input(name, value, type="text") -%} {%- endmacro %}
{% set alias = render_input %}
```
--------------------------------
### AND Logic Operator
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Example of using the 'and' operator to combine boolean expressions.
```html
{{ true and false }}
```
--------------------------------
### Render Template String
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/README.md
Shows how to render a template directly from a string using the -t option.
```bash
minijinja-cli -t "Hello {{ name }}" -D name=World
```
--------------------------------
### Basic HTML Structure with Jinja Blocks
Source: https://github.com/mitsuhiko/minijinja/blob/main/benchmarks/inputs/all_elements.html
Demonstrates the basic structure of a Minijinja HTML template using blocks for content insertion and inheritance.
```html
{% block title %}{% endblock %} | Hello {# this is a comment #} {% block html_body %}
Hello
=====
{% for item in site.nav %}* [{{ item.title|upper }}]({{ item.url }}) {% endfor %}
{% block body %}
{% for item in items %}* {{ loop.index }}: {{ item|upper }}
{% endfor %}
{% endblock %}
{% block footer %} {% with copyright=current_year() %} {% include "footer.html" %} {% endwith %} {% endblock %}
{% if DEBUG %}
{{ debug() }}
{% endif %} {% endblock html_body %}
```
--------------------------------
### Render Template with String and Integer Variables
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/README.md
Demonstrates rendering a template file using string and integer variables passed via the -D option.
```bash
minijinja-cli template.j2 -D name=World -D count:=3
```
--------------------------------
### Run All Tests
Source: https://github.com/mitsuhiko/minijinja/blob/main/CONTRIBUTING.md
Execute all tests for the MiniJinja project using the provided Makefile. This is a prerequisite before submitting a pull request.
```sh
make test
```
--------------------------------
### Negated Containment Operator Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Demonstrates using the 'not in' operator to check for non-membership.
```html
{{ 'apple' not in fruits }}
```
--------------------------------
### Query Builder with Limit
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/dsl/README.md
Demonstrates chaining the `limit` method to the query builder.
```console
$ cargo run -- "query('my_table').filter(is_active=true).limit(10)"
```
--------------------------------
### Initialize Namespace with Keyword Argument
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/namespace.txt
Initializes a namespace using a keyword argument 'found' set to true. The namespace's state is then rendered.
```jinja
{% set ns = namespace(found=true) %}
{{- ns }}
```
--------------------------------
### Initialize Namespace with Attribute and Render
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/namespace.txt
Initializes a namespace and directly sets a nested attribute 'foo.bar' to 42. The resulting namespace state is then rendered.
```jinja
{% set ns.foo = namespace() %}
{%- set ns.foo.bar = 42 %}
{{- ns }}
```
--------------------------------
### List Slicing: Specific Range
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/slicing.txt
Extracts a sublist within a specified start and end index.
```minijinja
{{ intrange[2:10] }}
```
--------------------------------
### View Cargo Tree
Source: https://github.com/mitsuhiko/minijinja/blob/main/README.md
Displays the dependency tree for a project using minijinja.
```bash
$ cargo tree
minimal v0.1.0 (examples/minimal)
└── minijinja v2.20.0 (minijinja)
└── serde v1.0.144
```
--------------------------------
### Run Comparison Benchmarks
Source: https://github.com/mitsuhiko/minijinja/blob/main/benchmarks/README.md
Command to run specific comparison benchmarks for the Minijinja project. The '-p benchmarks' flag targets the benchmarks crate, and '--bench comparison' specifies the benchmark file to run.
```bash
$ cargo bench -p benchmarks --bench comparison
```
--------------------------------
### String Slicing: Specific Range
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/slicing.txt
Extracts a substring within a specified start and end index.
```minijinja
{{ hello[2:10] }}
```
--------------------------------
### Build and Test MiniJinja Workspace
Source: https://github.com/mitsuhiko/minijinja/blob/main/CLAUDE.md
Commands to build the entire workspace and run the comprehensive test suite. For faster testing of the core library, use `cargo test -p minijinja --all-features`.
```bash
# Build entire workspace
make build
# Run comprehensive test suite (slow)
make test
# Run tests for core library only (always test all features!)
cargo test -p minijinja --all-features
```
--------------------------------
### Initialize Namespace with Dictionary Argument
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/namespace.txt
Initializes a namespace by passing a dictionary with the key 'found' set to true. The resulting namespace state is rendered.
```jinja
{% set ns = namespace({"found": true}) %}
{{- ns }}
```
--------------------------------
### Lint and Format Code with Make
Source: https://github.com/mitsuhiko/minijinja/blob/main/CLAUDE.md
Before committing, ensure code quality by running lint and format checks using the make utility.
```bash
make lint
make format
```
--------------------------------
### Configure Custom Syntax Delimiters (New)
Source: https://github.com/mitsuhiko/minijinja/blob/main/UPDATING.md
Illustrates the updated approach for configuring custom syntax delimiters in MiniJinja 2.0 using `SyntaxConfig::builder`.
```rust
use minijinja::{Environment, syntax::SyntaxConfig};
let mut env = Environment::new();
env.set_syntax(
SyntaxConfig::builder()
.block_delimiters("{ ", " }")
.variable_delimiters("${ ", " }")
.comment_delimiters("{* ", " *}")
.build()
.unwrap(),
);
```
--------------------------------
### Importing with Context and Trailing Comma
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/imports.txt
Import macros, include context, and use a trailing comma.
```minijinja
{% from "foo.html" import a as b, b as c, with context %}
```
--------------------------------
### Simple Integer Division
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/math.txt
Demonstrates basic integer division.
```minijinja
{{ 4 // 2 }}
```
--------------------------------
### Generate a Range of Numbers
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/functions.txt
The `range` function generates a sequence of numbers. It can be used to iterate over a specific count or a defined start, stop, and step.
```jinja
{{ range(10) }}
```
```jinja
{{ range(-5, 5) }}
```
```jinja
{{ range(-3, 3, 2) }}
```
```jinja
{{ range(5, -5, -2) }}
```
```jinja
{{ range(5, -4, -2) }}
```
--------------------------------
### Run Benchmarks
Source: https://github.com/mitsuhiko/minijinja/blob/main/benchmarks/README.md
Command to execute the benchmarks for the Minijinja project. This command uses Cargo, Rust's package manager and build system.
```bash
$ cargo bench
```
--------------------------------
### Basic Include with Variables
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/include.txt
Demonstrates how to include another template ('simple_include.txt') and pass variables to it using the 'with' block. The included template will have access to the 'variable' passed from the parent.
```jinja
{% with variable=42 %}
{% include "simple_include.txt" %}
{% endwith %}
```
--------------------------------
### Custom Finalizer for Rendering
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-py/README.md
Define a custom finalizer function to modify how values are rendered. This example handles None values by returning an empty string.
```python
from minijinja import Environment
def finalizer(value):
if value is None:
return ""
return NotImplemented
env = Environment(finalizer=finalizer)
assert env.render_str("{{ none }}") == ""
```
--------------------------------
### Basic For Loop
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Iterate over a sequence (e.g., a list of users) to display items. The loop runs from the first item to the last.
```minijinja
Members
{% for user in users %}
- {{ user.username }}
{% endfor %}
```
--------------------------------
### Run minijinja-cli with Template and Data Files
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/README.md
Executes the minijinja-cli tool to render a template file using data from a JSON file. The output is typically directed to stdout.
```shell
minijinja-cli my-template.j2 data.json
```
--------------------------------
### List Slicing: Negative Start and End Reverse
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/slicing.txt
Extracts elements in reverse order from the fifth element from the end up to (but not including) the second element from the end.
```minijinja
{{ intrange[-5:2:-1] }}
```
--------------------------------
### Render Template with JSON Input from Stdin
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/README.md
Illustrates rendering a template using JSON data piped from stdin, specifying the input format with -f json.
```bash
echo '{"name": "World"}' | minijinja-cli -f json template.j2 -
```
--------------------------------
### Line Statement Block Definition
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/lexer-inputs/line-statement.txt
Define blocks using line statements for concise syntax. The '#' prefix indicates the start and end of the block definition.
```html
# block foo
# endblock
```
--------------------------------
### Format Code
Source: https://github.com/mitsuhiko/minijinja/blob/main/CONTRIBUTING.md
Format the codebase using the provided Makefile. This ensures code style consistency and is checked in CI.
```sh
make format
```
--------------------------------
### Run All Tests with Make
Source: https://github.com/mitsuhiko/minijinja/blob/main/CLAUDE.md
Execute all project tests using the make test command to ensure code integrity.
```bash
make test
```
--------------------------------
### Silent Undefined Behavior Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Demonstrates that an undefined value from an 'if' expression without an 'else' block prints as an empty string, even with strict undefined behavior enabled.
```minijinja
{{ value if false }}
```
--------------------------------
### Basic MiniJinja Template Structure
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Illustrates a minimal template with blocks, loops, and comments.
```html
{% block title %}My Website{% endblock %}
My Webpage
{% block body %}{% endblock %}
{# a comment #}
```
--------------------------------
### Importing a Template as an Alias
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/imports.txt
Import an entire template file and assign it an alias.
```minijinja
{% import "foo.html" as x %}
```
--------------------------------
### Dynamic Context Template
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-go/examples/dynamic_context/template.txt
A Minijinja template that displays the process ID, current working directory, and environment variables. It uses a for loop to iterate over sorted environment variables.
```minijinja
pid: {{ pid }}
current_dir: {{ cwd }}
env:
{%- for key, value in env|dictsort %}
{{ key }}: {{ value }}
{%- endfor %}
```
--------------------------------
### Include with Context
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/include.txt
Includes 'foo.txt' and passes the current template's context to it.
```jinja
{% include "foo.txt" with context %}
```
--------------------------------
### Calling Self-Referential and Custom Functions
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/call.txt
Shows how to call methods on self and custom functions with various argument types.
```minijinja
{{ self.foo() }}
{{ foo(1, 2, a=3, b=4) }}
```
--------------------------------
### Importing Multiple Macros with Aliases
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/imports.txt
Import multiple macros, each with its own alias.
```minijinja
{% from "foo.html" import a as b, b as c %}
```
--------------------------------
### Incorrect Loop Unpacking Example
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/loop_bad_unpacking_wrong_len.txt
This Jinja template code attempts to unpack sequences of length 3 into two variables, which will cause an unpacking error. This highlights the importance of matching the number of loop variables to the structure of the data being iterated over.
```jinja
{% for a, b in seq %}
{{ a }}: {{ b }}
{% endfor %}
```
--------------------------------
### Simple Float Division
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/math.txt
Demonstrates basic float division.
```minijinja
{{ 4 / 2 }}
```
--------------------------------
### Template Error with Traceback
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/error/README.md
This example shows a template error that includes a traceback, indicating the nested nature of the error. It displays the source code of the failing template, the line number, and the specific part of the expression that caused the error. It also lists the referenced variables at the point of failure.
```console
$ cargo run
template error: could not render include: error in "include.txt" (in hello.txt:8)
---------------------------------- hello.txt ----------------------------------
5 | {% with foo = 42 %}
6 | {{ range(10) }}
7 | {{ other_seq|join(" ") }}
8 > {% include "include.txt" %}
i ^^^^^^^^^^^^^^^^^^^^^ could not render include
9 | {% endwith %}
10 | {% endwith %}
11 | {% endfor %}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Referenced variables: {
foo: 42,
other_seq: [
0,
1,
2,
3,
4,
],
range: minijinja::functions::builtins::range,
}
-------------------------------------------------------------------------------
caused by: invalid operation: tried to use + operator on unsupported types number and string (in include.txt:1)
--------------------------------- include.txt ---------------------------------
1 > Hello {{ item_squared + bar }}!
i ^^^^^^^^^^^^^^^^^^ invalid operation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Referenced variables: {
bar: "test",
item_squared: 4,
}
-------------------------------------------------------------------------------
```
--------------------------------
### Importing Multiple Macros
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/imports.txt
Import multiple macros from a template file.
```minijinja
{% from "foo.html" import a, b %}
```
--------------------------------
### Define and Alias a Minijinja Macro
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/macros/src/macros.html
Demonstrates defining a macro named 'render_input' and creating an alias for it.
```jinja
{% macro render_input(name, value, type="text") -%} {%- endmacro %} {% set alias = render_input %}
```
--------------------------------
### Create Dictionary by Merging and Adding
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/dict.txt
Use the `dict` function to merge an existing dictionary and add new key-value pairs.
```minijinja
{{ dict(d, c=3)}}
```
--------------------------------
### Basic Variable Access with `with`
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/with.txt
Demonstrates how to assign variables within a template using the `with` statement and access them.
```jinja
{% with a=foo, b=bar %}
{{ a }}|{{ b }}|{{ other }}
{% endwith %}
```
--------------------------------
### Basic If-Elif-Else Structure
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/if_cond.txt
Demonstrates the standard conditional branching in Minijinja using if, elif, and else. This structure allows for multiple conditions to be evaluated sequentially.
```minijinja
{% if expr1 %}
branch 1
{% elif expr2 %}
branch 2
{% elif expr3 %}
branch 3
{% else %}
else
{% endif %}
```
--------------------------------
### Using Context with RenderCtx
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-go/README.md
Demonstrates how to pass a Go context.Context to the RenderCtx function for managing timeouts and cancellation. Ensure to defer the cancel function call.
```go
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defuncancel()
```
```go
result, err := tmpl.RenderCtx(ctx, data)
```
--------------------------------
### Importing Macro with Alias
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/imports.txt
Import a macro and assign it an alias.
```minijinja
{% from "foo.html" import a as b %}
```
--------------------------------
### Include First Existing Template from List (Ignore Missing)
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Includes the first existing template from a list, falling back to rendering nothing if none are found. Use when all options are optional.
```jinja
{% include ['special_sidebar.html', 'sidebar.html'] ignore missing %}
```
--------------------------------
### Render Basic Variables and Environment
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/dynamic-context/src/template.txt
This snippet shows how to render simple variables like 'pid' and 'cwd', and iterate over environment variables within a Minijinja template.
```jinja
pid: {{ pid }}
current_dir: {{ cwd }}
env:
{%- for key, value in env|dictsort %}
{{ key }}: {{ value }}
{%- endfor %}
```
--------------------------------
### Test Minimal and Optimized Feature Sets
Source: https://github.com/mitsuhiko/minijinja/blob/main/CLAUDE.md
Commands to test specific feature combinations for the MiniJinja core library, including minimal configurations and performance optimizations.
```bash
# Test minimal feature set
cd minijinja && cargo test --no-default-features --features=debug
# Test with performance optimizations
cd minijinja && cargo test --no-default-features --features=speedups
# Test specific feature combinations
cd minijinja && cargo test --features=json,urlencode,custom_syntax
```
--------------------------------
### Initialize and Update Namespace Variable
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/namespace.txt
Initializes a namespace, sets an attribute 'foo' to 0, and then accumulates values into 'foo' within a loop. The final state of the namespace is then rendered.
```jinja
{%-
set ns = namespace() %}
{%- set ns.foo = 0 %}
{%- for count in range(10) %}
{%- set ns.foo = ns.foo + count %}
{%- endfor %}
{{- ns }}
```
--------------------------------
### Create Dictionary with Key-Value Pairs
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/dict.txt
Use the `dict` function to create a new dictionary by providing key-value pairs directly.
```minijinja
{{ dict(x=1, y=2) }}
```
--------------------------------
### Run Single Test with All Features
Source: https://github.com/mitsuhiko/minijinja/blob/main/CONTRIBUTING.md
Execute a specific test file, such as test_vm, using Cargo. Ensure all features are enabled by passing --all-features.
```sh
cargo test test_vm --all-features
```
--------------------------------
### Tuple Unpacking with `with`
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/with.txt
Shows how to unpack tuples into variables using the `with` statement.
```jinja
{% with (a, b, (c,)) = tuple %}
{{ a }}|{{ b }}|{{ c }}
{% endwith %}
```
--------------------------------
### Render Template with Data File
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/long_help.txt
Basic usage: renders a template file using a JSON data file for context.
```bash
minijinja-cli hello.j2 hello.json
```
--------------------------------
### Basic Query Builder Usage
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/dsl/README.md
Shows the basic usage of the query builder with a filter operation.
```console
$ cargo run -- "query('my_table').filter(is_active=true)"
```
--------------------------------
### Run Specific Test Files in Minijinja
Source: https://github.com/mitsuhiko/minijinja/blob/main/CLAUDE.md
Navigate to the minijinja directory and execute tests for specific files like test_filters or test_templates.
```bash
cd minijinja && cargo test --test test_filters
cd minijinja && cargo test --test test_templates
```
--------------------------------
### Importing Macros and Variables
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/macro_import2.txt
Imports macros and variables from 'include_with_var_and_macro.txt' and uses them to render content. Demonstrates accessing imported variables and calling imported macros.
```jinja
{% import "include_with_var_and_macro.txt" as helpers -%}
{{ dict(helpers) }}
missing: {{ helpers.missing }}
title: {{ helpers.title }}
helper: {{ helpers.helper("a", "b") }}
```
--------------------------------
### Importing a Single Macro
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/imports.txt
Import a single macro from a template file.
```minijinja
{% from "foo.html" import a %}
```
--------------------------------
### Feature Testing Combinations
Source: https://github.com/mitsuhiko/minijinja/blob/main/AGENTS.md
Commands for testing specific feature sets of the minijinja crate. Includes testing minimal features, performance optimizations, and custom feature combinations.
```bash
# Test minimal feature set
cd minijinja && cargo test --no-default-features --features=debug
```
```bash
# Test with performance optimizations
cd minijinja && cargo test --no-default-features --features=speedups
```
```bash
# Test specific feature combinations
cd minijinja && cargo test --features=json,urlencode,custom_syntax
```
--------------------------------
### Using break and continue in Minijinja Loops
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/loop_controls.txt
Demonstrates the use of `continue` to skip odd numbers and `break` to exit the loop when the item exceeds 5. The output will show only even numbers up to 4.
```jinja
{% for item in range(10) -%}
{%- if item is odd %}{% continue %}{% endif %}
{%- if item > 5 %}{% break %}{% endif %}
{{- item }}
{%- endfor %}
```
--------------------------------
### Build and Test Workspace
Source: https://github.com/mitsuhiko/minijinja/blob/main/AGENTS.md
Commands to build the entire Cargo workspace and run the comprehensive test suite. Also includes a command to run tests for the core library with all features enabled.
```bash
# Build entire workspace
make build
```
```bash
# Run comprehensive test suite (slow)
make test
```
```bash
# Run tests for core library only (always test all features!)
cargo test -p minijinja --all-features
```
--------------------------------
### Highlight Rust Code
Source: https://github.com/mitsuhiko/minijinja/blob/main/examples/syntax-highlighting/src/example.html
This snippet demonstrates how to highlight Rust code using the Minijinja `highlight` macro. It sets a specific syntax theme before rendering the code.
```html
{% set SYNTAX_THEME = "base16-ocean.light" %} {% call highlight('rust') %} fn main() { println!("Hello World!"); } {% endcall %}
```
--------------------------------
### Registering a Custom Function in Go
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-go/README.md
Demonstrates adding a custom function named 'now' that returns the current time formatted as RFC3339. This function does not accept arguments or keyword arguments.
```go
env := minijinja.NewEnvironment()
env.AddFunction("now", func(state *minijinja.State, args []value.Value, kwargs map[string]value.Value) (value.Value, error) {
return value.FromString(time.Now().Format(time.RFC3339)), nil
})
```
--------------------------------
### Define a simple macro
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/macros.txt
Defines a basic macro named 'foo' with no arguments.
```jinja
{% macro foo() %}...{% endmacro %}
```
--------------------------------
### Run Specific Test by Name in Minijinja
Source: https://github.com/mitsuhiko/minijinja/blob/main/CLAUDE.md
Navigate to the minijinja directory and run a specific test by its name, capturing output.
```bash
cd minijinja && cargo test test_function_name -- --nocapture
```
--------------------------------
### Range and Multiplication in Minijinja
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/mul.txt
Demonstrates multiplying the result of a range function. Note that range itself does not directly support multiplication for repetition.
```minijinja
{{ range(3) * 3 }}
```
--------------------------------
### Importing Macros from a File
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/macro_import.txt
Imports macros 'title', 'helper', and 'missing' from 'include_with_var_and_macro.txt'. The imported macros and variables are then rendered.
```jinja
{% from "include_with_var_and_macro.txt" import title, helper, missing -%}
missing: {{ missing }}
title: {{ title }}
helper: {{ helper("a", "b") }}
```
--------------------------------
### Inequality Comparison
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Demonstrates checking for inequality between two values.
```html
{{ 1 != 2 }}
```
--------------------------------
### For Loop with Cycle Helper
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Use the `loop.cycle` helper to alternate between values (e.g., 'odd' and 'even' classes) for each iteration.
```minijinja
{% for row in rows %}
{{ row }}
{% endfor %}
```
--------------------------------
### Keyword Arguments in Minijinja
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/calls-and-literals.txt
Pass arguments by name using keyword syntax. This improves readability and allows for non-ordered arguments.
```minijinja
{{ get_args(1, 2, one=1, two=two) }}
```
--------------------------------
### Using 'html' Autoescape Mode
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/autoescape.txt
Illustrates using the 'html' mode for autoescaping, which is often the default for HTML contexts.
```jinja
{% autoescape "html" %}{{ unsafe }}{% endautoescape %}
```
--------------------------------
### Set Rust Toolchain to 1.63.0
Source: https://github.com/mitsuhiko/minijinja/blob/main/CONTRIBUTING.md
Configure the project to use Rust 1.63.0 by creating a rust-toolchain.toml file. This ensures compatibility with the project's MSRV.
```toml
[toolchain]
channel = "1.63.0"
```
--------------------------------
### Define and Call a Basic Macro
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/macro_basic.txt
Define a macro `add` that concatenates two arguments with a separator. Shows various ways to call the macro with positional and keyword arguments.
```jinja
{% macro add(a, b) %}{{ a }}|{{ b }}{% endmacro -%}
{{ add(1, 2) }}
{{ add(a=1, b=2) }}
{{ add(b=2, a=1) }}
{{ add(1, b=2) }}
```
--------------------------------
### Macro with Keyword Arguments
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/macro_kwargs.txt
Defines a macro that accepts multiple keyword arguments and demonstrates calling it with varying numbers of arguments.
```jinja
{% macro foo(a, b, c, d) %}{{ [a, b, c, d] }}{% endmacro -%}
{{ foo(1, 2, 3) }}
{{ foo({"blub": "blah"}) }}
{{ foo(a=1, b=2, c=3) }}
{{ foo(a=1, b=2, c=3, d=4) }}
```
--------------------------------
### Mixed Positional, Unpacked Iterables, and Unpacked Dictionaries in Minijinja
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/calls-and-literals.txt
Demonstrates a complex function call combining positional arguments, unpacked iterables, and unpacked dictionaries.
```minijinja
{{ get_args(1, *[2], one=1, **dict(two=two)) }}
```
--------------------------------
### Importing without Context
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/imports.txt
Import macros and explicitly exclude context.
```minijinja
{% from "foo.html" import a as b, b as c without context %}
```
--------------------------------
### Defining and Rendering a Basic Block
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/inputs/block.txt
This snippet shows how to define a default block content and render it. The `var` variable is passed to the template context.
```jinja
{% block title %}{% endblock %}
{% block body %}{{ var }}{% endblock body %}
```
--------------------------------
### Define a Card Macro
Source: https://github.com/mitsuhiko/minijinja/blob/main/benchmarks/inputs/macro_heavy.html
This macro generates a card component displaying an item's title, description, metadata, and actions.
```minijinja
{% macro card(item) %}
### {{ item.title }}
{{ item.description }}
{% for key, val in item.metadata|items %}
{{ key|title }}
{{ val }}
{% endfor %}
{% if item.actions %}
{% for action in item.actions %} [{{ action.label }}]({{ action.url }}) {% endfor %}
{% endif %}
{% endmacro %}
```
--------------------------------
### Simple Fragment Rendering
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/fragment-inputs/fragment_simple.txt
Renders a fragment containing a variable. The variable 'var' is expected to be 'foo'.
```html
{% block title %}Shouldn't show up{% endblock %}
{% block fragment %}{{ var }}{% endblock fragment %}
Also shouldn't show up
```
--------------------------------
### Configuring custom delimiters in Rust
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-cli/src/syntax_help.txt
Shows how to configure custom block, variable, and comment delimiters for MiniJinja templates using Rust code.
```rust
let mut environment = Environment::new();
environment.set_syntax(SyntaxConfig::builder()
.block_delimiters("\\BLOCK{", "}")
.variable_delimiters("\\VAR{", "}")
.comment_delimiters("\\#{", "}")
.build()
.unwrap()
);
```
--------------------------------
### Importing without Context and Trailing Comma
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja/tests/parser-inputs/imports.txt
Import macros, exclude context, and use a trailing comma.
```minijinja
{% from "foo.html" import a as b, b as c, without context %}
```
--------------------------------
### Render Template String
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-js/README.md
Renders a template directly from a string. Ensure the Environment is imported.
```typescript
import { Environment } from "minijinja-js";
const env = new Environment();
env.debug = true;
const result = env.renderStr('Hello {{ name }}!', { name: 'World' });
console.log(result);
```
--------------------------------
### Resolve Includes from Filesystem
Source: https://github.com/mitsuhiko/minijinja/blob/main/minijinja-js/README.md
Configures the environment to load templates and resolve includes from the filesystem using Node.js modules. Requires setting a path join callback and a loader.
```typescript
import { Environment } from "minijinja-js";
import fs from "node:fs";
import path from "node:path";
const env = new Environment();
// Resolve relative paths like "./partial.html" against the parent template
env.setPathJoinCallback((name, parent) => {
const parentDir = parent ? path.dirname(parent) : process.cwd();
const joined = path.resolve(parentDir, name);
return joined.replace(/\\/g, '/');
});
// Synchronous loader: return template source or null/undefined if missing
env.setLoader((name) => {
try {
return fs.readFileSync(name, "utf8");
} catch {
return null;
}
});
// Example: main in-memory, include from disk under ./templates/dir/inc.html
const templatePath = path.resolve(process.cwd(), "templates/dir/main.html");
env.addTemplate(templatePath, "Hello {% include './inc.html' %}!");
console.log(env.renderTemplate(templatePath, { value: "World" }));
// -> Hello [World]!
```
--------------------------------
### Accept or Reject Snapshot Test Changes
Source: https://github.com/mitsuhiko/minijinja/blob/main/CLAUDE.md
Commands using the `insta` crate to manage snapshot tests. Use `--accept` to update snapshots or `--reject` to revert changes.
```bash
cargo insta test --accept # accept changes
cargo insta test --reject # reject changes
```