Skip to content

Template functions and attributes ​

Registering ​

cg_component::register adds the template functions to MiniJinja (the starter already does this):

rust
// src/app.rs
.with_views(|views, _| {
    cg_component::register(views);
})

With a bare MiniJinja Environment (in tests, say), use cg_component::jinja::add_functions(&mut env).

The functions ​

FunctionParametersOutput
cg_badge(label, …)color, size, icon, rounded, attrsBadge
cg_button(label, …)color, size, variant, icon, icon_position, icon_only, disabled, type, name, value, attrsButton
cg_icon(name, …)size, label, attrsIcon
cg_head()—For the layout's <head>: CSRF, render token and endpoint meta tags
cg_html_attrs()—For the layout's <html>: data-cg-endpoints="m-…"

cg_head() and cg_html_attrs() output the values the share_head middleware prepared for this request; without that middleware (for example non-GET or AJAX requests) they output an empty string.

Escaping ​

  • Text is always escaped, with the same rules as PHP's e() (& < > " ' → &amp; &lt; &gt; &quot; &#039;), so the output matches Blade character for character.
  • Only values marked safe are treated as HTML: the |safe filter, the output of caller(), and the return values of other template functions.
jinja
{{ cg_badge("<b>Bold</b>") }}            {# shows the characters <b>Bold</b> #}
{{ cg_badge("<b>Bold</b>"|safe) }}       {# bold; only do this with strings you hard-coded #}

{% call cg_button_with_body() %}…{% endcall %}   {# caller() in your own macro counts as safe too #}

Pass component HTML from Rust with View::with_html(name, html) and write {{ name }} in the template; it isn't escaped twice.

Strict parameters ​

  • Unknown parameters are errors (kwargs.assert_all_used()), so a misspelled colour= isn't silently ignored.
  • An invalid option value produces an error listing the valid values: color 不支援 [red];可用:neutral, primary, success, warning, danger, info。
  • Rules like an unregistered icon name or icon-only without an icon return a template error (the Rust builder panics instead).

During development, template errors are shown on the error page; with APP_DEBUG=false users only see a 500.

attrs ​

attrs is a map, with the same rules as PHP's attributes():

jinja
{{ cg_button("Submit", attrs={
    "class": ["w-full", "mt-4"],
    "data-linker-call": "save",
    "data-x": 1,
    "hidden": false,
    "autofocus": true,
    "title": none,
}) }}
ValueOutput
String, numbername="value" (escaped)
truename=""
false, noneNothing
A string or array for classAppended after the component's own classes
Anything else (maps, other arrays)A template error

Attribute names must match ^[A-Za-z_:][A-Za-z0-9:._-]*$ (on click, for example, isn't allowed).

Attributes ​

On the Rust side the same rules are cg_component::Attributes, which functions like runtime::render_object also return:

rust
use cg_component::{AttributeValue, Attributes};

let mut attrs = Attributes::default();
attrs.set("data-x", "1");
attrs.set("class", "extra more");     // class is split and appended
attrs.set("hidden", true);            // → hidden=""
attrs.set("data-x", "2");             // same name: keeps its position, replaces the value
attrs.set("skipped", false);          // not output

assert_eq!(attrs.render(&["base"]), r#" class="base extra more" data-x="2" hidden="""#);
MethodDescription
set(name, value)value takes &str, String, bool, integers, f64; panics on an invalid name
add_classes(iter)Appends several classes, skipping empty strings
merge(other)Merges another set; attributes with the same name take other's value
get(name)Option<&AttributeValue>
render(default_classes)Outputs class="defaults yours" other="…", with a leading space when there's anything

A component's .attribute(..), .class(..) and .attributes(..) all wrap this. Order rules:

  1. The component's own classes (the render argument)
  2. The classes you add, in the order added
  3. Other attributes, in the order first set

Runtime attributes in templates ​

Call runtime::render_object and friends in the handler, turn the result into a string and pass it to the template:

rust
view("page", data! {})
    .with_html("panel_attrs", Html::raw(runtime::render_object("panel", &[Allow::StateRead]).render(&[])))
html
<section{{ panel_attrs }}>…</section>

The result of render(&[]) already starts with a space, so write it right after the tag name.