MiniJinja templates

laravel-rust-format Alpha Laravel for Rust

Used in production across multiple projects.

The adapter’s default minijinja feature provides the filters below. Register the provider or install the filters directly. The framework’s built-in date, for_humans, round and title retain their usual behavior.

Use an example expression in an interpolation to print its result. Signatures show optional arguments with defaults. Arguments can be positional in signature order or passed by name. Outputs show rendered HTML. A displayed \n represents a newline.

{{ "id:42"|str_after(":") }}

PHP functions

FilterPHP equivalentExample expressionOutput
number_format(decimals=0, dec_point=".", thousands_sep=",")number_format1.005|number_format(2)1.01
php_round(precision=0, mode="HalfAwayFromZero")round4.0|php_round|php_echo4
php_echoNumeric echo or cast to string(0.1 + 0.2)|php_echo0.3
ucfirstucfirst"élan"|ucfirstélan
php_lcfirstlcfirst"HELLO"|php_lcfirsthELLO
php_ucwords(separators=none)ucwords"one-two three"|php_ucwords("-")One-Two three
php_strtolowerstrtolower"CAFÉ"|php_strtolowercafÉ
php_strtoupperstrtoupper"café"|php_strtoupperCAFé
php_nl2br(is_xhtml=true)nl2br"<b>line</b>\nnext"|php_nl2br(is_xhtml=false)&lt;b&gt;line&lt;&#x2f;b&gt;&lt;br&gt;\nnext
php_str_pad(length, pad=" ", side=1)str_pad"x"|php_str_pad(4, "-", side=2)-x--
php_wordwrap(width=75, line_break="\n", cut_long_words=false)wordwrap"one two"|php_wordwrap(4, " / ")one &#x2f; two
php_strip_tags(allowed_tags=none)strip_tags"<b>bold</b><i>italic</i>"|php_strip_tags(["b"])&lt;b&gt;bold&lt;&#x2f;b&gt;italic

php_round returns a float, including for whole results. Pipe it to php_echo for PHP 8.4’s numeric output. (-0.4)|php_round|php_echo renders as -0, and 1e15|php_round|php_echo renders as 1.0E+15. php_ucwords uses PHP’s default whitespace delimiters when separators is omitted or none. For php_str_pad, the side is 0 for left, 1 for right, or 2 for both. The byte-oriented php_str_pad and php_wordwrap report InvalidOperation if a cut splits a UTF-8 character. Padding and wrapping also report this error if the requested output cannot be allocated.

The optional mode= keyword accepts a PHP case name such as "HalfEven", or an integer mode such as 3. Both make 2.5|php_round(mode="HalfEven")|php_echo render as 2.

FilterArgumentsExample expressionResult before HTML autoescaping
php_trimcharacters=none"abc!cab"|php_trim("a..c")!
php_ltrimcharacters=none"__id__"|php_ltrim("_")id__
php_rtrimcharacters=none"__id__"|php_rtrim("_")__id
arr_joinglue, final_glue=""["a", "b", "c"]|arr_join(", ", final_glue=" and ")a, b and c
php_implodeseparator=""[12, false, "x"]|php_implode("/")12//x
php_explodeseparator, limit=9223372036854775807"a,b,c"|php_explode(",", limit=2)["a", "b,c"]
php_array_filter["0", "00", false, 4]|php_array_filterKeys 1 and 3 with values "00" and 4
php_array_values{"z": 7, "a": 2}|php_array_values[7, 2]
php_json_encodeflags=0, depth=512 plus named overrides"👋/"|php_json_encode(flags=64, unescaped_unicode=true)"👋/"
blade_jsonflags=15, depth=512"</script>"|blade_json"\u003C\/script\u003E"
js_fromflags=0, depth=512"</script>"|js_from'\u003C\/script\u003E'
php_edouble_encode=true"&amp;<"|php_e(double_encode=false)&amp;&lt;
php_sprintfVariadic positional values"%04d %s"|php_sprintf(7, "items")0007 items
php_vsprintfvalues (sequence or map)"%04d %s"|php_vsprintf([7, "items"])0007 items
php_str_starts_withneedle"été"|php_str_starts_with("")True
str_containsneedles, ignore_case=false"CAFÉ"|str_contains(["", "Fé"], ignore_case=true)True
str_starts_withneedles"été"|str_starts_with(["", "é"])True
str_ends_withneedles"été"|str_ends_with("")False
str_substrstart, length=none"a猫b"|str_substr(-2, -1)猫
str_length"a猫b"|str_length3
str_match_allpattern"3 x 12"|str_match_all("/([0-9]+)|x/")["3", "", "12"]

The PHP trim filters use PHP’s byte character masks, including ranges such as "a..z". Template strings require valid UTF-8. A mask or printf format that splits a character produces a template error. The str_substr and str_length filters work in Unicode characters. Laravel’s str_contains, str_starts_with and str_ends_with accept a string or sequence and ignore empty needles. PHP’s php_str_starts_with accepts a single string and matches an empty needle.

The PHP array helpers preserve MiniJinja's iteration order. Canonical string keys such as "1" become PHP integer keys. php_array_filter removes PHP-false values, including the string "0", and preserves keys. php_array_values produces a sequence. php_explode treats zero as a limit of one and negative limits drop trailing pieces.

All three encoders accept a PHP integer flag bitmask and an array depth, and render null as null. Named booleans override the corresponding mask bits.

KeywordPHP flagBit
hex_tagJSON_HEX_TAG1
hex_ampJSON_HEX_AMP2
hex_aposJSON_HEX_APOS4
hex_quotJSON_HEX_QUOT8
unescaped_slashesJSON_UNESCAPED_SLASHES64
pretty_printJSON_PRETTY_PRINT128
unescaped_unicodeJSON_UNESCAPED_UNICODE256
preserve_zero_fractionJSON_PRESERVE_ZERO_FRACTION1024
force_objectJSON_FORCE_OBJECT16
numeric_checkJSON_NUMERIC_CHECK32
partial_output_on_errorJSON_PARTIAL_OUTPUT_ON_ERROR512
unescaped_line_terminatorsJSON_UNESCAPED_LINE_TERMINATORS2048
invalid_utf8_ignoreJSON_INVALID_UTF8_IGNORE1048576
invalid_utf8_substituteJSON_INVALID_UTF8_SUBSTITUTE2097152
throw_on_errorJSON_THROW_ON_ERROR4194304

blade_json emits raw JSON with the four Blade HEX flags by default. With those defaults, use it for an expression in a script element or in a single-quoted data attribute. A supplied mask replaces the defaults, so preserve the HEX flags when encoding untrusted data into HTML. js_from emits the raw JavaScript expression for Blade’s @js directive and always adds Laravel’s required flags. Use it as an expression in a script element. Its apostrophes delimit JavaScript strings. For HTML attributes, use php_json_encode with HTML autoescaping to store JSON as data. php_e applies Laravel HTML escaping once and marks the result safe. Its double_encode=false setting preserves recognized entities.

Strings

Filter or functionPHP equivalentExample expressionOutput
str_append(parts…)Str::of($value)->append(...)"item "|str_append(7, true)item 71
str_prepend(parts…)Str::of($value)->prepend(...)"end"|str_prepend("first ", "second ")first second end
str_limit(limit=100, end="...", preserve_words=false)Str::limit"東京"|str_limit(2)東...
str_words(words=100, end="...")Str::words"one, two three"|str_words(2)one, two...
str_slug(separator="-", language="en")Str::slug"Café Mañana & Co."|str_slugcafe-manana-co
str_ascii(language="en")Str::ascii"Ärger"|str_ascii("de")Aerger
str_titleStr::title"džEMAL 1st"|str_titleDžemal 1St
str_headlineStr::headline"emailNotificationSent"|str_headlineEmail Notification Sent
str_ucfirstStr::ucfirst"élan"|str_ucfirstÉlan
str_lcfirstStr::lcfirst"ÉLAN"|str_lcfirstéLAN
str_upperStr::upper"Straße"|str_upperSTRASSE
str_lowerStr::lower"CAFÉ"|str_lowercafé
str_plural(count=2, prepend_count=false)Str::plural"city"|str_plural(3, prepend_count=true)3 cities
str_singularStr::singular"CHILDREN"|str_singularCHILD
plural(word, count)Str::pluralplural("criterion", 2)criteria
str_after(search)Str::after"id:42"|str_after(":")42
str_after_last(search)Str::afterLast"a:b:c"|str_after_last(":")c
str_before(search)Str::before"id:42"|str_before(":")id
str_before_last(search)Str::beforeLast"a:b:c"|str_before_last(":")a:b
str_between(from, to)Str::between"[a][b]"|str_between("[", "]")a][b
str_between_first(from, to)Str::betweenFirst"[a][b]"|str_between_first("[", "]")a
str_camelStr::camel"user name"|str_cameluserName
str_snake(delimiter="_")Str::snake"UserName"|str_snake(delimiter=".")user.name
str_studly(normalize=false)Str::studly"user name"|str_studlyUserName
str_kebabStr::kebab"UserName"|str_kebabuser-name
str_mask(character, index, length=none)Str::mask"abcdef"|str_mask("*", 1, length=3)a***ef
str_pad_left(length, pad=" ")Str::padLeft"猫"|str_pad_left(3, "-")--猫
str_pad_right(length, pad=" ")Str::padRight"猫"|str_pad_right(3, "-")猫--
str_pad_both(length, pad=" ")Str::padBoth"猫"|str_pad_both(4, "-")-猫--
str_replace(search, replacement, case_sensitive=true)Str::replace"Été"|str_replace("é", "x", case_sensitive=false)xtx
str_squishStr::squish" one\t two "|str_squishone two
str_word_wrap(width=75, line_break="\n", cut_long_words=false)Str::wordWrap"one two"|str_word_wrap(4, " / ")one &#x2f; two
str_apaStr::apa"notes from the road"|str_apaNotes From the Road
str_initials(capitalize=false)Str::initials"ada lovelace"|str_initials(capitalize=true)AL
str_match(pattern)Str::match"ID-42"|str_match("/ID-([0-9]+)/")42
str_is_match(pattern)Str::isMatch"ID-42"|str_is_match("/^ID-/")True
str_replace_matches(pattern, replacement, limit=-1)Str::replaceMatches"blue blue"|str_replace_matches("/blue/", "red", limit=1)red blue
str_markdown(html_input="allow", allow_unsafe_links=true, soft_break="\n")Str::markdown"**hello**"|str_markdown&lt;p&gt;&lt;strong&gt;hello&lt;&#x2f;strong&gt;&lt;&#x2f;p&gt;\n
str_inline_markdown(html_input="allow", allow_unsafe_links=true, soft_break="\n")Str::inlineMarkdown"**hello**<br>"|str_inline_markdown(html_input="strip")&lt;strong&gt;hello&lt;&#x2f;strong&gt;\n

Pass @language=nonetostr_slug to skip transliteration. The filter uses the default dictionary. For a custom dictionary, use [Slug` in Rust](strings.md#transliteration-and-slugs).

str_replace and str_replace_matches accept a sequence of searches or patterns and a scalar replacement or a parallel sequence. Each step sees the result of the previous step. Missing entries in the replacement sequence mean the empty string. The regex limit applies per pattern.

Numbers

FilterPHP equivalentExample expressionOutput
number_format_intl(precision=none, max_precision=none, locale=none)Number::format1234.56789|number_format_intl1,234.568
number_file_size(precision=0, max_precision=none, locale=none)Number::fileSize2560|number_file_size(max_precision=2)2.5 KB
number_percentage(precision=0, max_precision=none, locale=none)Number::percentage50|number_percentage(1)50.0%
number_currency(code=none, precision=none, locale=none)Number::currency1234.5|number_currency("JPY")¥1,234
number_abbreviate(precision=0, max_precision=none, locale=none)Number::abbreviate999.5|number_abbreviate1K
number_for_humans(precision=0, max_precision=none, abbreviate=false, locale=none)Number::forHumans1200|number_for_humans(max_precision=2)1.2 thousand
number_ordinal(locale=none)Number::ordinal1|number_ordinal(locale="fr")1er
number_spell(locale=none, after=none, until=none)Number::spell100000|number_spell(locale="en_IN")one lakh
number_spell_ordinal(locale=none)Number::spellOrdinal12|number_spell_ordinal(locale="de")zwölfte

max_precision wins when both precision arguments are set. The base precision still controls whether the zero branch of number_abbreviate and number_for_humans localizes zero. Without either, number_format_intl uses up to three fractional digits. number_currency uses the configured default code when code is omitted, none, "" or "0". Currency-specific digits apply when precision is omitted. A code rejected by the formatter raises a template error. Supply a locale such as "fr" for localized decimals, percentages, currencies and magnitude labels. The same locale= argument selects the spellout and ordinal rules available in the core crate. See Parity for the included locales. To enable the extra rule sets in an application that uses the adapter, add a dependency on the core crate with the number-locale-all feature.

Dates and relative times

Use interval_for_humans(short=false, parts=-1, join=false, locale="en", cascade=false) for a stored ISO duration or integer seconds. It formats the duration without an application clock.

{{ 5400|interval_for_humans(join=true, cascade=true) }}
{{ "PT1H30M"|interval_for_humans(locale="fr", join=true) }}

These render as 1 hour and 30 minutes and 1 heure et 30 minutes. A malformed ISO duration or a fractional number of seconds is a template error. Build bounded periods in the view model and pass their ISO text or collected dates to the template.

FilterPHP equivalentExample expressionOutput
carbon_parse(tz=none)Carbon::parse($value, $tz)"2024-02-29"|carbon_parse(tz="Europe/Paris")|carbon_date_string2024-02-29
carbon_modify(modifier, tz=none)$date->modify($modifier)"2024-01-31"|carbon_modify("+1 month")|carbon_date_string2024-03-02
php_strtotime(base_timestamp=none, tz=none)strtotime($value, $baseTimestamp)"+1 week"|php_strtotime(0)|carbon_format("Y-m-d")1970-01-08
carbon_create_from_format(format, tz=none)Carbon::createFromFormat($format, $value, $tz)"2024-02"|carbon_create_from_format("!Y-m")|carbon_date_string2024-02-01
carbon_date_time_string(precision="second", tz=none)$date->toDateTimeString($precision)"2024-02-29T12:15:07Z"|carbon_date_time_string("minute")2024-02-29 12:15
carbon_format(format, tz=none)$date->format($format)"2026-12-03"|carbon_format("l jS F")Thursday 3rd December
carbon_iso8601$date->toIso8601String()"2026-12-03T14:30:07+01:00"|carbon_iso86012026-12-03T14:30:07+01:00
carbon_iso_string(tz=none, keep_offset=false)$date->toISOString($keepOffset)"2026-12-03T14:30:07.123456+01:00"|carbon_iso_string2026-12-03T13:30:07.123456Z
carbon_date_string$date->toDateString()"2026-12-03T14:30:07+01:00"|carbon_date_string2026-12-03
diff_for_humans(other=none, …)$date->diffForHumans($other, …)"2026-12-03T12:00:00Z"|diff_for_humans(other="2026-12-03T14:30:00Z", parts=2, join=true)2 hours and 30 minutes before
carbon_iso_format(format, locale="en")$date->isoFormat($format)zoned|carbon_iso_format("LLLL", locale="fr")mardi 14 juillet 2026 09:00
carbon_translated_format(format, locale="en")$date->translatedFormat($format)zoned|carbon_translated_format("l j F", locale="fr")mardi 14 juillet
carbon_calendar(reference, locale="en")$date->calendar($reference)zoned|carbon_calendar(other, locale="fr")Aujourd’hui à 09:00
carbon_diff_for_humans_in(other, locale="en")$date->diffForHumans($other)zoned|carbon_diff_for_humans_in(other, locale="fr")2 heures avant

The localized examples use zoned = "2026-07-14T09:00:00+02:00[Europe/Brussels]" and other = "2026-07-14T11:30:00+02:00[Europe/Brussels]". Use diff_for_humans(locale="fr", parts=2, join=true) for the localized builder options. The carbon_diff_for_humans_in shorthand uses a single part and an explicit comparison date. Carbon locale codes fall back through installed parent locales to English.

Date filters accept ISO strings or Unix seconds, including fractional seconds. An explicit tz converts instants and interprets civil dates in that zone. With no override, Unix seconds and strings ending in Z are displayed in FORMATTING_TIMEZONE. Civil dates and times use UTC, and numeric offsets and named zones are preserved. The constructors carbon_parse and carbon_create_from_format interpret civil values in the configured zone and preserve embedded zones. carbon_parse accepts the free-form date grammar and requires the application clock for expressions with inherited fields. carbon_modify uses the input date as its clock. php_strtotime uses the application clock when base_timestamp is omitted, and returns false on an invalid expression. carbon_create_from_format gets inherited fields from the application clock. For standalone templates, supply a complete pattern or reset missing fields with ! or |. carbon_iso_string renders in UTC by default. Pass keep_offset=true to keep the offset.

Supply other for comparison wording. With other=none or omitted, the filter reads the Laravel application clock. For standalone registration, pass other explicitly. Application clock and time zone

Use keyword arguments for longer calls. The table gives the positional order and defaults.

ArgumentDefaultEffect
othernoneComparison date
shortfalseCompact unit labels
parts1Maximum part count. Use -1 for all parts.
joinnonetrue for an locale’s conjunction, or a string for custom glue
just_nowfalseCarbon’s JUST_NOW flag
minimum_unitnoneCarbon’s minimumUnit name or shortcut
skip[]List of unit names, plurals or shortcuts
options0Carbon’s integer flag mask
last_gluenoneFinal separator, used with string-valued join
syntax"auto"Also accepts "absolute", "relative_to_now" and "relative_to_other".
a_unitfalseCarbon’s aUnit option
no_zero_difffalseNO_ZERO_DIFF
one_day_wordsfalseONE_DAY_WORDS
two_day_wordsfalseTWO_DAY_WORDS
sequential_parts_onlyfalseSEQUENTIAL_PARTS_ONLY
roundfalseROUND
floorfalseFLOOR
ceilfalseCEIL
tznoneDisplay zone
locale"en"Carbon translations for the full options builder

A true flag argument adds the flag to options. See Dates for the flag effects and precedence.

Clock helpers

FunctionExample
now(){{ now()|carbon_format("Y-m-d H:i", tz="Europe/Brussels") }}
time(){{ time() }}
php_date(format, tz=none){{ php_date("Y") }} or {{ "Y"|php_date }}

The clock helpers require a Laravel application context and follow test travel and freeze. Register this adapter after the optional minijinja-contrib helpers to use the Laravel clock’s now().

Missing values, errors and HTML

  • A none or undefined filter input renders as an empty string, except the three JSON and JavaScript encoders, which emit null. plural behaves the same when its word is absent.
  • Text filters take strings. Numeric filters and plural counts accept numbers, numeric strings and booleans. Booleans are converted to 0 or 1. Pass a sequence’s length explicitly as the plural count.
  • An invalid date, malformed numeric string, rejected currency code, unsupported syntax or duplicate argument causes a MiniJinja error. Missing required arguments and extra positional or keyword arguments also cause errors for present inputs. carbon_iso_string renders an empty string for year zero, because Carbon returns null there.
  • Results use normal MiniJinja escaping in HTML. Use MiniJinja’s built-in escape or e for template escaping and php::e in Rust when you need the exact PHP string. Calling both on the same text can double-escape it.
  • php_nl2br and the Markdown filters return ordinary strings. MiniJinja escapes their tags in HTML views. Apply safe only to HTML you trust. Markdown's PHP defaults permit raw HTML and unsafe links. The filters accept html_input="escape" or "strip" and allow_unsafe_links=false.

Split and scan text

{% for field in tags|str_split("/[,;] */u", flags=1) %}{{ field }}{% endfor %}
{% set id, count = record|str_scan("ID=%d; count=%d") %}
{% if enabled|str_to_boolean %}{{ id }} ({{ count }}){% endif %}

str_split accepts PHP's numeric flags and defaults to limit=-1, flags=0. Use flag 1 to skip empty fields, 2 to include captured delimiters and 4 for [text, byte_offset] pairs. str_scan returns typed fields, including null for unassigned slots. str_to_boolean accepts the trimmed, case-insensitive tokens 1, true, on and yes.

Community package, not affiliated with Laravel.