### indent
Source: https://keats.github.io/tera
Indents a string by injecting a prefix at the start of each line.
```APIDOC
## indent
### Description
Indents a string by injecting a prefix at the start of each line. The `width` argument (default 4) specifies how many spaces to insert per line. If the `first` argument (default false) is set true, spaces are inserted for the first line. If the `blank` argument (default false) is set true, spaces are inserted for blank/whitespace lines.
```
--------------------------------
### get
Source: https://keats.github.io/tera
Accesses a value from an object using a key.
```APIDOC
## get
### Description
Accesses a value from an object when the key is not a standard Tera identifier.
### Parameters
- **key** (string) - Required - The key to access.
- **default** (any) - Optional - A value to return if the key is missing.
```
--------------------------------
### Slice arrays and strings
Source: https://keats.github.io/tera
Access subsets of arrays or strings using Python-style [start:stop:step] syntax.
```tera
{{ numbers[0] }}
{{ numbers[-1] }}
{{ numbers[:-1] }}
{{ numbers[:2] }}
{{ numbers[1:2] }}
{{ numbers[0:2:2] }}
{{ numbers[::-1] }}
{{ product.name[-1] }}
{{ product.name[::-1] }}
{{ product.name[1:] }}
{{ product.name[:-1] }}
```
--------------------------------
### Apply trim filters
Source: https://keats.github.io/tera
Removes whitespace or specific patterns from the start or both ends of a string.
```tera
{{ value | trim(pat="|") }}
{{ value | trim_start(pat="|") }}
```
--------------------------------
### Initialize and load templates
Source: https://keats.github.io/tera
Create a Tera instance and load templates either via glob patterns or manually.
```rust
use tera::Tera;
let mut tera = Tera::default();
// with the `glob_fs` feature enabled
tera.load_from_glob("templates/**/*.html")?;
// or by hand
tera.add_raw_templates(vec![
("hello.html", include_str!("templates/hello.html")),
("index.html", include_str!("templates/index.html")),
("products/product.html", include_str!("templates/products/product.html")),
("products/price.html", include_str!("templates/price.html")),
])?;
```
--------------------------------
### Check string prefix with starting_with
Source: https://keats.github.io/tera
Validates if a string variable begins with a specific pattern.
```Tera
{% if path is starting_with(pat="x/") %}
In section x
{% endif %}
```
--------------------------------
### Including Templates
Source: https://keats.github.io/tera
Include other templates using static paths. Dynamic paths are not supported.
```tera
{% include "included.html" %}
```
```tera
{% include "partials/" ~ name ~ ".html" %}
```
--------------------------------
### Invoke components in templates
Source: https://keats.github.io/tera
Demonstrates usage of self-closing tags and block-style components, including shorthand variable passing.
```tera
{{}}
{{}}
{% %}
This is a widget!
{{}}
{% %}
```
--------------------------------
### Add Tera dependency
Source: https://keats.github.io/tera
Add the Tera crate to your Cargo.toml file.
```toml
tera = "2"
```
--------------------------------
### Spread syntax for objects and arrays
Source: https://keats.github.io/tera
Create new objects or arrays by spreading existing ones, similar to JavaScript.
```tera
{% set m = {...base, "d": 4} %}
```
```tera
{{ [0, ...numbers, 99] }}
```
--------------------------------
### Tera::load_from_glob
Source: https://keats.github.io/tera
Loads templates from the filesystem using a glob pattern. Requires the `glob_fs` feature.
```APIDOC
## tera.load_from_glob(pattern: &str)
### Description
Loads templates from the filesystem based on a glob pattern. The template name is derived from the file path relative to the glob root.
### Parameters
- **pattern** (str) - Required - A glob pattern string (e.g., "templates/**/*.html")
```
--------------------------------
### Invoke block-style components
Source: https://keats.github.io/tera
Shows how to pass content into a component body using the block syntax.
```tera
{% %}
This is a widget!
{{}}
{% %}
```
--------------------------------
### Iterating with For Loops
Source: https://keats.github.io/tera
Loops support arrays, strings, maps, and structs. Special loop variables provide iteration metadata.
```tera
{% for product in products %}
{{loop.index}}. {{product.name}}
{% endfor %}
```
```tera
{% for letter in name %}
{% if loop.index % 2 == 0%}
{{ letter }}
{% else %}
{{ letter }}
{% endif %}
{% endfor %}
```
```tera
{% for key, value in products %}
{{key}}. {{value.name}}
{% endfor %}
```
```tera
{% for product in products | reverse %}
{{loop.index}}. {{product.name}}
{% endfor %}
```
```tera
{% for a in [1,2,3,] %}
{{a}}
{% endfor %}
```
```tera
{% for product in products %}
{{loop.index}}. {{product.name}}
{% else %}
No products.
{% endfor %}
```
```tera
{% for product in products %}
{% if product.id == target_id %}{% break %}{% endif %}
{{loop.index}}. {{product.name}}
{% endfor %}
```
```tera
{% for product in products %}
{% if loop.index is even %}{% continue %}{% endif %}
{{loop.index}}. {{product.name}}
{% endfor %}
```
--------------------------------
### Tera::add_raw_templates
Source: https://keats.github.io/tera
Adds templates directly from strings.
```APIDOC
## tera.add_raw_templates(templates: Vec<(&str, &str)>)
### Description
Registers multiple templates provided as raw strings. Each tuple contains the template name and the template content.
### Parameters
- **templates** (Vec<(&str, &str)>) - Required - A vector of tuples where the first element is the template name and the second is the template content.
```
--------------------------------
### Define a basic component
Source: https://keats.github.io/tera
Uses the component/endcomponent tags to define a reusable UI element with optional default parameter values.
```tera
{% component button(label, variant = "primary") %}
{% endcomponent button %}
```
--------------------------------
### Tera::render
Source: https://keats.github.io/tera
Renders a template by name using the provided context.
```APIDOC
## tera.render(name: &str, context: &Context)
### Description
Renders the specified template using the data provided in the Context.
### Parameters
- **name** (str) - Required - The name of the template to render.
- **context** (Context) - Required - The context object containing data for the template.
```
--------------------------------
### Set global context
Source: https://keats.github.io/tera
Define variables that are automatically available in every template render.
```rust
tera.global_context().insert("name", "John Doe");
```
--------------------------------
### Register multiple components
Source: https://keats.github.io/tera
Defines several namespaced components for use throughout the application.
```tera
{% component ui.button(label: string, variant: string = "primary", ...attrs) %}
{% endcomponent ui.button %}
{% component forms.input(name: string, label: string, required: bool = false) %}
{% endcomponent forms.input %}
{% component ui.forms.widget(title: string) %}
{{title}}
{{body}}
{% endcomponent ui.forms.widget %}
```
--------------------------------
### Render templates with context
Source: https://keats.github.io/tera
Use Context to pass data to templates and render them. The context! macro provides a convenient way to serialize data.
```rust
use tera::Context;
let mut context = Context::new();
context.insert("age", &24);
context.insert("product", &product);
// if you already have a Value, you can do the following to avoid serialization
context.insert_value("product2", product_value);
// There is also a `context!` macro which will always serialize
let context = context! {
age => &24,
product => &product,
};
tera.render("hello.html", &context)?;
```
--------------------------------
### join
Source: https://keats.github.io/tera
Joins an array with a string separator.
```APIDOC
## join
### Description
Joins an array with a string.
### Example
`{{ value | join(sep=" // ") }}`
```
--------------------------------
### Add template comments
Source: https://keats.github.io/tera
Wrap content in {# #} to prevent it from being rendered.
```tera
{# A comment #}
```
--------------------------------
### Configure auto-escaping
Source: https://keats.github.io/tera
Customize which file extensions trigger auto-escaping or disable it entirely.
```rust
// escape only files ending with `.php.html`
tera.autoescape_on(vec![".php.html"]);
// disable autoescaping completely
tera.autoescape_on(vec![]);
```
--------------------------------
### Apply title filter
Source: https://keats.github.io/tera
Capitalizes the first letter of each word in a string.
```tera
{{ value | title }}
```
--------------------------------
### Assigning Variables
Source: https://keats.github.io/tera
Use set for local scope or set_global to modify the global context. Assignments can also capture blocks of content.
```tera
{% set my_var = "hello" %}
{% set my_var = 1 + 4 %}
{% set my_var = some_var %}
{% set my_var = %}
{% set my_var = global_fn() %}
{% set my_var = [1, true, some_var | round] %}
```
```tera
{% set_global my_var = "hello" %}
{% set_global my_var = 1 + 4 %}
{% set_global my_var = some_var %}
{% set_global my_var = %}
{% set_global my_var = global_fn() %}
{% set_global my_var = [1, true, some_var | round] %}
```
```tera
{% set hero | upper | trans(lang="fr") %}
Hello {{ world }}
{% endset %}
```
--------------------------------
### Tera::autoescape_on
Source: https://keats.github.io/tera
Configures which file extensions should have auto-escaping enabled.
```APIDOC
## tera.autoescape_on(extensions: Vec<&str>)
### Description
Sets the list of file extensions that will trigger auto-escaping. Passing an empty vector disables auto-escaping entirely.
### Parameters
- **extensions** (Vec<&str>) - Required - A list of file extensions (e.g., vec![".html", ".xml"]).
```
--------------------------------
### default
Source: https://keats.github.io/tera
Provides a default value if the variable is not present in the context.
```APIDOC
## default
### Description
Returns the provided default value if the variable is missing from the context.
### Parameters
- **value** (any) - Required - The value to return if the variable is missing.
- **boolean** (bool) - Optional - If set to true, the filter checks for truthiness instead of existence.
```
--------------------------------
### Convert to string
Source: https://keats.github.io/tera
Returns the string representation of a value.
```tera
{{ value | str }}
```
--------------------------------
### Using If Conditionals
Source: https://keats.github.io/tera
Conditional logic follows Python syntax. Undefined variables are treated as falsy.
```tera
{% if price < 10 or always_show %}
Price is {{ price }}.
{% elif price > 1000 and not rich %}
That's expensive!
{% else %}
N/A
{% endif %}
```
```tera
{% if my_var %}
{{ my_var }}
{% else %}
Sorry, my_var isn't defined.
{% endif %}
```
--------------------------------
### Perform list comprehension
Source: https://keats.github.io/tera
Transform and filter collections using list comprehension syntax.
```tera
{{ [a for a in numbers if a is odd] }}
{{ [x if x > 1 else 0 for x in numbers] }}
{{ [a | str | safe for a in numbers] | safe }}
{{ [(a * 2) + 1 for a in numbers] }}
{{ [v for k, v in data] | safe }}
{{ [x for x in numbers if x > 100] }}
```
--------------------------------
### keys
Source: https://keats.github.io/tera
Returns an array of keys from a map.
```APIDOC
## keys
### Description
Returns an array of the keys of a map.
```
--------------------------------
### Implement a custom test
Source: https://keats.github.io/tera
Implement the Test trait for a struct to create complex custom tests.
```rust
#[derive(Debug, Default)]
pub struct Matching {
cache: RwLock>,
}
impl Test<&str, TeraResult> for Matching {
fn call(&self, val: &str, kwargs: Kwargs, _: &State) -> TeraResult {
let pat = kwargs.must_get::<&str>("pat")?;
let regex = get_or_create_regex(&self.cache, pat)?;
Ok(regex.is_match(val))
}
}
```
--------------------------------
### Define a custom filter
Source: https://keats.github.io/tera
Create a simple filter function that transforms input values.
```rust
pub fn upper(val: &str, _: Kwargs, _: &State) -> String {
val.to_uppercase()
}
```
--------------------------------
### pairs
Source: https://keats.github.io/tera
Returns an array of [key, value] pairs from a map.
```APIDOC
## pairs
### Description
Returns an array of [key, value] pairs from a map.
```
--------------------------------
### Convert newlines to HTML breaks
Source: https://keats.github.io/tera
Replaces line breaks with tags. Use the safe filter if the template is auto-escaped.
```tera
{{ value | newlines_to_br }}
```
--------------------------------
### Test expressions with if blocks
Source: https://keats.github.io/tera
Use the is keyword to perform conditional tests on expressions.
```tera
{% if my_number is odd %}
Odd
{% endif %}
```
```tera
{% if my_number is not odd %}
Even
{% endif %}
```
--------------------------------
### Define an open component with spread operator
Source: https://keats.github.io/tera
Collects extra parameters into a map named 'rest' by using the spread operator in the component definition.
```tera
{% component button(label: string, variant = "primary", ...rest) %}
{% endcomponent button %}
```
--------------------------------
### nth
Source: https://keats.github.io/tera
Returns the nth element of an array.
```APIDOC
## nth
### Description
Returns the nth element of an array. If the array is empty, returns None. It takes a required `n` argument, corresponding to the 0-based index you want to get.
### Example
`{{ value | nth(n=2) }}`
```
--------------------------------
### Extend a base template
Source: https://keats.github.io/tera
Child templates use the 'extends' tag to inherit from a base template and override specific blocks. Use 'super()' to render the parent block's content.
```html
{% extends "base.html" %}
{% block title %}Index{% endblock title %}
{% block head %}
{{/* super() */}}
{% endblock head %}
{% block content %}
Index
Welcome to my awesome homepage.
{% endblock content %}
```
--------------------------------
### Truncate strings
Source: https://keats.github.io/tera
Shortens a string to a specified length, optionally appending a custom suffix.
```tera
{{ value | truncate(length=10) }}
```
```tera
{{ value | truncate(length=10, end="") }}
```
--------------------------------
### Extract keys from grouped map
Source: https://keats.github.io/tera
Demonstrates extracting keys from a map produced by group_by into a separate array for custom ordering.
```tera
{% set map = section.pages | group_by(attribute="year") %}
{% set_global years = [] %}
{% for year, ignored in map %}
{% set_global years = [...years, year] %}
{% endfor %}
{% for year in years | reverse %}
{% set posts = map[year] %}
{% endfor %}
```
--------------------------------
### Convert map to pairs
Source: https://keats.github.io/tera
Returns an array of [key, value] pairs from a map, which can then be sorted.
```tera
{{ my_map | pairs }}
```
--------------------------------
### Use default filter
Source: https://keats.github.io/tera
Provides a default value if the variable is not present in the context. The boolean parameter can be used to check for truthiness instead of existence.
```tera
{% if value %}{{ value }}{% else %}1{% endif %}
```
```tera
I would like to read more {{ "" | default (value="Louise Michel") }}!
```
```tera
I would like to read more {{ "" | default (value="Louise Michel", boolean=true) }}!
```
--------------------------------
### Concatenate strings and identifiers
Source: https://keats.github.io/tera
Use the ~ operator to join strings, numbers, or identifiers into a single string.
```tera
{{ "hello " ~ 'world' ~ `!` }}
{{ an_ident ~ " and a string" ~ another_ident }}
{{ an_ident ~ another_ident }}
```
--------------------------------
### values
Source: https://keats.github.io/tera
Returns an array of values from a map.
```APIDOC
## values
### Description
Returns an array of the values of a map.
```
--------------------------------
### Split string into array
Source: https://keats.github.io/tera
Divides a string into an array based on a provided pattern.
```tera
{{ path | split(pat="/") }}
```
--------------------------------
### Apply filter sections
Source: https://keats.github.io/tera
Use the filter tag to apply a filter to a block of content.
```tera
{% filter my_filter(param="value") %}
some content {{ var }}
{% endfilter %}
```
--------------------------------
### Implement nested blocks
Source: https://keats.github.io/tera
Tera supports nested blocks across multiple levels of inheritance. The 'super()' function allows child templates to access and extend parent block content.
```html
// grandparent
{% block hey %}hello{% endblock hey %}
// parent
{% extends "grandparent" %}
{% block hey %}hi and grandma says {{/* super() */}} {% block ending %}sincerely{% endblock ending %}{% endblock hey %}
// child
{% extends "parent" %}
{% block hey %}dad says {{/* super() */}}{% endblock hey %}
{% block ending %}{{/* super() */}} with love{% endblock ending %}
```
--------------------------------
### newlines_to_br
Source: https://keats.github.io/tera
Replaces line breaks with HTML tags.
```APIDOC
## newlines_to_br
### Description
Replaces line breaks (\n or \r\n) with HTML line breaks ( ).
### Example
`{{ value | newlines_to_br }}`
```
--------------------------------
### Controlling Whitespace in Templates
Source: https://keats.github.io/tera
Use hyphens within tags to trim surrounding whitespace. This applies to statements, expressions, and comments.
```tera
{% set my_var = 2 %}
{{ my_var }}
```
```tera
2
```
```tera
{% set my_var = 2 -%}
{{ my_var }}
```
--------------------------------
### Attach metadata to a component
Source: https://keats.github.io/tera
Associates JSON-like metadata with a component, which is accessible only via the Rust API.
```tera
{% component array(greeting: string) {"css": "./array.css"} %}
Hello
{% endcomponent %}
```
--------------------------------
### pluralize
Source: https://keats.github.io/tera
Returns a plural suffix based on the value.
```APIDOC
## pluralize
### Description
Returns a plural suffix if the value is not equal to 1, or a singular suffix otherwise. The plural suffix defaults to `s` and the singular suffix defaults to the empty string.
### Example
`{{ num_categories | pluralize(singular="y", plural="ies") }}`
```
--------------------------------
### trim_end
Source: https://keats.github.io/tera
Removes trailing whitespace or a specific pattern from a string.
```APIDOC
## trim_end
### Description
Removes trailing whitespace if the variable is a string. Also takes an optional `pat` argument to trim by that pattern instead of whitespace.
### Example
`{{ value | trim_end(pat="|") }}`
```
--------------------------------
### Define a base template
Source: https://keats.github.io/tera
A base template defines the document structure and provides blocks that child templates can override.
```html
{% block head %}
{% block title %}{% endblock title %} - My Webpage
{% endblock head %}
{% block content %}{% endblock content %}
```
--------------------------------
### Apply safe filter
Source: https://keats.github.io/tera
Marks content as safe to prevent HTML escaping. Must be the final filter in the chain to be effective.
```tera
{{ content | replace(from="Robert", to="Bob") | safe }}
{{ content | safe | replace(from="Robert", to="Bob") }}
```
--------------------------------
### round
Source: https://keats.github.io/tera
Returns a number rounded following the method given.
```APIDOC
## round
### Description
Returns a number rounded following the method given. Default behaviour is to round to the nearest integer. `ceil` and `floor` are available as alternative methods. Another optional argument, `precision`, is available to select the precision of the rounding.
### Example
`{{ num | round }} {{ num | round(method="ceil", precision=2) }}`
```
--------------------------------
### Join array elements
Source: https://keats.github.io/tera
Concatenates array elements into a single string using a separator.
```tera
{{ value | join(sep=" // ") }}
```
--------------------------------
### group_by
Source: https://keats.github.io/tera
Groups an array into a map based on a specified attribute.
```APIDOC
## group_by
### Description
Groups an array into a map where keys are the stringified values of the attribute and values are arrays of elements sharing that attribute.
### Parameters
- **attribute** (string) - Required - The attribute to group the array elements by.
```
--------------------------------
### Check membership with in operator
Source: https://keats.github.io/tera
Verify if a value exists within an array, string, or map.
```tera
{{ some_var in [1, 2, 3] }}
{{ 'index' in page.path }}
{{ an_ident not in an_obj }}
```
--------------------------------
### truncate
Source: https://keats.github.io/tera
Truncates a string to a specified length.
```APIDOC
## truncate
### Description
Truncates a string to the indicated length. If the string has a smaller length than the `length` argument, the string is returned as is. By default, the filter will add an ellipsis at the end if the text was truncated.
### Example
`{{ value | truncate(length=10, end="") }}`
```
--------------------------------
### Group array by attribute
Source: https://keats.github.io/tera
Groups an array into a map based on a specified attribute. Missing or null attributes are discarded.
```rust
struct Author {
name: String,
};
struct Post {
content: String,
year: u32,
author: Author,
}
```
```tera
{{ posts | group_by(attribute="year") }}
```
```tera
{% for name, author_posts in posts | group_by(attribute="author.name") %}
{{ name }}
{% for post in author_posts %}
{{ post.year }}: {{ post.content }}
{% endfor %}
{% endfor %}
```
--------------------------------
### Access array elements by index
Source: https://keats.github.io/tera
Retrieves the element at a specific 0-based index from an array.
```tera
{{ value | nth(n=2) }}
```
--------------------------------
### Preventing Template Rendering with Raw Blocks
Source: https://keats.github.io/tera
Use the raw block to output text containing Tera delimiters without processing them.
```tera
{% raw %}
Hello {{ name }}
{% endraw %}
```
--------------------------------
### sort
Source: https://keats.github.io/tera
Sorts an array into ascending order based on values or a specific attribute.
```APIDOC
## sort
### Description
Sorts an array into ascending order. Numbers are sorted numerically, strings alphabetically, arrays by length, and booleans with false before true.
### Parameters
- **attribute** (string) - Optional - The field name or path to sort by when dealing with structs or tuples.
```
--------------------------------
### Apply replace filter
Source: https://keats.github.io/tera
Replaces occurrences of a substring with a new string using named arguments.
```tera
{{ name | replace(from="Robert", to="Bob")}}
```
--------------------------------
### Check containment with containing
Source: https://keats.github.io/tera
Checks if a string, array, or map contains the specified argument.
```Tera
{% if username is containing(pat="xXx") %}
Bad
{% endif %}
```
--------------------------------
### Pluralize text
Source: https://keats.github.io/tera
Appends a suffix based on whether the value is singular or plural.
```tera
You have {{ num_messages }} message{{ num_messages | pluralize }}
```
```tera
{{ num_categories }} categor{{ num_categories | pluralize(singular="y", plural="ies") }}
```
--------------------------------
### Calculate absolute value
Source: https://keats.github.io/tera
Returns the absolute value of a number.
```tera
{{ negative_number | abs }}
```
--------------------------------
### Check divisibility with divisible_by
Source: https://keats.github.io/tera
Determines if a numeric expression is divisible by a provided divisor.
```Tera
{% if rating is divisible_by(divisor=2) %}
Divisible
{% endif %}
```
--------------------------------
### Trim trailing characters
Source: https://keats.github.io/tera
Removes trailing whitespace or a specific pattern from a string.
```tera
{{ value | trim_end(pat="|") }}
```
--------------------------------
### unique
Source: https://keats.github.io/tera
Removes duplicate items from an array.
```APIDOC
## unique
### Description
Removes duplicate items from an array.
```
--------------------------------
### Sort array by attribute
Source: https://keats.github.io/tera
Sorts an array of structs or tuples using the attribute argument to specify the field.
```rust
struct Name(String, String);
struct Person {
name: Name,
age: u32,
}
```
```tera
{{ people | sort(attribute="name.1") }}
```
```tera
{{ people | sort(attribute="age") }}
```
--------------------------------
### Round numbers
Source: https://keats.github.io/tera
Rounds a number using a specified method and precision.
```tera
{{ num | round }} {{ num | round(method="ceil", precision=2) }}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.