#16

Product support

Visit this product's website for support.

Categories

  • Developer Tools
  • Miscellaneous

Twig extensions plugin adds new filters and functions to your templates! No other plugin dependencies.

Features

  • supported filters strftime, uppercase, lowercase, ucfirst, lcfirst, ltrim, rtrim, str_repeat, plural, truncate, wordwrap, strpad, leftpad, rightpad, rtl, shuffle, time_diff, localizeddate, localizednumber, localizedcurrency, mailto, var_dump
  • supported functions config, session, trans, var_dump, template_from_string
  • special filter mailto for rendering encrypted email as spam prevention

Available filters

strftime, uppercase, lowercase, ucfirst, lcfirst, ltrim, rtrim, str_repeat, plural, truncate, wordwrap, strpad, leftpad, rightpad, rtl, shuffle, time_diff, localizeddate, localizednumber, localizedcurrency, mailto, var_dump

strftime

Format a local time/date according to locale settings.

Posted at {{ article.date | strftime('%d.%m.%Y %H:%M:%S') }}

The example would output Posted at 04.01.2016 22:57:42. See more format parameters.

uppercase

Make a string uppercase

Hello I'm {{ 'Jack' | uppercase }}

The example would output Hello I'm JACK.

lowercase

Make a string lowercase

Hello I'm {{ 'JACK' | lowercase }}

The example would output Hello I'm jack.

ucfirst

Make a string's first character uppercase

Hello I'm {{ 'jack' | ucfirst }}

The example would output Hello I'm Jack.

lcfirst

Make a string's first character lowercase

Hello I'm {{ 'Jack' | lcfirst }}

The example would output Hello I'm jack.

ltrim

Strip whitespace (or other characters) from the beginning of a string

Hello I'm {{ ' jack' | ltrim }}

The example would output Hello I'm jack without whitespaces from the start.

rtrim

Strip whitespace (or other characters) from the end of a string.

Hello I'm {{ 'jack ' | rtrim }}

The example would output Hello I'm jack without whitespaces from the end.

str_repeat

Repeat a string

I'm the {{ 'best' | str_repeat(3) }}!

The example would output I'm the best best best!

plural

Get the plural form of an English word.

You have {{ count }} new {{ 'mail' | plural(count) }}

The example would output You have 1 new mail or You have 3 new mails - depending on mails count.

truncate

Use the truncate filter to cut off a string after limit is reached

{{ "Hello World!" | truncate(5) }}

The example would output Hello..., as ... is the default separator.

You can also tell truncate to preserve whole words by setting the second parameter to true. If the last Word is on the the separator, truncate will print out the whole Word.

{{ "Hello World!" | truncate(7, true) }}

Here Hello World! would be printed.

If you want to change the separator, just set the third parameter to your desired separator.

{{ "Hello World!" | truncate(7, false, "??") }}

This example would print Hello W??.

wordwrap

Use the wordwrap filter to split your text in lines with equal length.

{{ "Lorem ipsum dolor sit amet, consectetur adipiscing" | wordwrap(10) }}

This example would print:

Lorem ipsu  
m dolor si  
t amet, co  
nsectetur  
adipiscing  

The default separator is "\n", but you can easily change that by providing one:

{{ "Lorem ipsum dolor sit amet, consectetur adipiscing" | wordwrap(10, "zz\n") }}

This would result in:

Lorem ipsuzz  
m dolor sizz  
t amet, cozz  
nsectetur zz  
adipiscing  

rtl

Reverse a string.

{{ 'Hello world!' | rtl }}

This would print:

!dlrow olleH

shuffle

Shuffle an array

{{ songs | shuffle }}

time_diff

Use the time_diff filter to render the difference between a date and now.

{{ post.published_at | time_diff }}

The example above will output a string like 4 seconds ago or in 1 month, depending on the filtered date.

time_diff arguments

  • date: The date for calculate the difference from now. Can be a string or a DateTime instance.
  • now: The date that should be used as now. Can be a string or a DateTime instance. Do not set this argument to use current date.

time_diff translation

To get a translatable output, give a Symfony\Component\Translation\TranslatorInterface as constructor argument. The returned string is formatted as diff.ago.XXX or diff.in.XXX where XXX can be any valid unit: second, minute, hour, day, month, year.

localizeddate

Use the localizeddate filter to format dates into a localized string representating the date.

{{ post.published_at | localizeddate('medium', 'none', locale) }}

The localizeddate filter accepts strings (it must be in a format supported by the strtotime function), DateTime instances, or Unix timestamps.

localizeddate arguments

  • date_format: The date format. Choose one of these formats:
    • 'none': IntlDateFormatter::NONE
    • 'short': IntlDateFormatter::SHORT
    • 'medium': IntlDateFormatter::MEDIUM
    • 'long': IntlDateFormatter::LONG
    • 'full': IntlDateFormatter::FULL
  • time_format: The time format. Same formats possible as above.
  • locale: The locale used for the format. If NULL is given, Twig will use Locale::getDefault()
  • timezone: The date timezone
  • format: Optional pattern to use when formatting or parsing. Possible patterns are documented in the ICU user guide.

localizednumber

Use the localizednumber filter to format numbers into a localized string representating the number.

{{ product.quantity | localizednumber }}

Internally, Twig uses the PHP NumberFormatter::create() function for the number.

localizednumber arguments

  • style: Optional date format (default: 'decimal'). Choose one of these formats:
    • 'decimal': NumberFormatter::DECIMAL
    • 'currency': NumberFormatter::CURRENCY
    • 'percent': NumberFormatter::PERCENT
    • 'scientific': NumberFormatter::SCIENTIFIC
    • 'spellout': NumberFormatter::SPELLOUT
    • 'ordinal': NumberFormatter::ORDINAL
    • 'duration': NumberFormatter::DURATION
  • type: Optional formatting type to use (default: 'default'). Choose one of these types:
    • 'default': NumberFormatter::TYPE_DEFAULT
    • 'int32': NumberFormatter::TYPE_INT32
    • 'int64': NumberFormatter::TYPE_INT64
    • 'double': NumberFormatter::TYPE_DOUBLE
    • 'currency': NumberFormatter::TYPE_CURRENCY
  • locale: The locale used for the format. If NULL is given, Twig will use Locale::getDefault()

localizedcurrency

Use the localizedcurrency filter to format a currency value into a localized string.

{{ product.price | localizedcurrency('EUR') }}

localizedcurrency arguments

  • currency: The 3-letter ISO 4217 currency code indicating the currency to use.
  • locale: The locale used for the format. If NULL is given, Twig will use Locale::getDefault()

mailto

Filter for rendering email as normal mailto link, but with encryption against bots!

{{ '[email protected]' | mailto }}

returns

<span id="e846043876">[javascript protected email address]</span><script type="text/javascript">/*<![CDATA[*/eval("var a=\"[email protected]_+Rvf\";var b=a.split(\"\").sort().join(\"\");var c=\"[email protected]\";var d=\"\";for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));document.getElementById(\"e846043876\").innerHTML=\"<a href=\\\"mailto:\"+d+\"\\\">\"+d+\"</a>\"")/*]]>*/</script>

which will be rendered to page as normal

<a href="mailto:[email protected]">[email protected]</a>

PHP encrypts your email address and generates the JavaScript that decrypts it. Most bots can't execute JavaScript and that is what makes this work. A visitors of your web page will not notice that you used this script as long as they has JavaScript enabled. The visitors will see "[javascript protected email address]" instead of the email address if they has JavaScript disabled.

You can also use additional filter parameters

{{ '[email protected]' | mailto(true, true) }}

Where first parameter means "returns email with mailto link" and you can set it to false. Second parameter means "encryption is enabled".

var_dump

Dumps information about a variable.

<pre>{{ users | var_dump }}</pre>

Available functions

config, session, trans, var_dump, template_from_string

config

Function transports the functionality of the Laravel config() helper function to Twig.

{{ config('app.locale') }}

The example would output the value currently stored in app.locale. See more about the Laravel config helper function here.

session

Function transports the functionality of the Laravel session() helper function to Twig.

{{ session('my.session.key') }}

The example would output the value currently stored in my.session.key. See more about the Laravel session helper function here.

trans

Function transports the functionality of the Laravel trans() helper function to Twig.

{{ trans('acme.blog::lang.app.name') }}

The example would output a value stored in a localization file of an imaginary blog plugin. See more about localization in October CMS here.

var_dump

Dumps information about a variable. Can be also used as filter.

<pre>{{ var_dump(users) }}</pre>

template_from_string

Function loads a template from a string.

{% set name = 'John' %}
{{ include(template_from_string("Hello {{ name }}")) }}
{{ include(template_from_string("Hurry up it is: {{ "now"|date("m/d/Y") }}")) }}

Buy me a coffee

Installation

Just install VojtaSvoboda.TwigExtensions plugin a you can use new added plugin at your templates:

<h1 class="heading">{{ article.heading | uppercase }}</h1>
<p class="created">
    Posted at {{ article.date | strftime('%d.%m.%Y %H:%M:%S') }}
</p>
<p class="perex">
    {{ article.perex | truncate(80) }}
</p>

Contributing

Do you want some extra feature or fix bug? Send me pull request or create issue, please.

Code check

Codacy

Unit tests

Build Status

License

Twig extensions plugin is open-sourced software licensed under the MIT license same as OctoberCMS platform.

Icon made by Freepik from www.flaticon.com.

  • Found the plugin useful on 18 Jan, 2017

    Very usefull plugin! Thank you very much!

  • Found the plugin useful on 9 Jan, 2017

    Great work!

    Excellent plugin

    Thanks Vojta Svoboda

  • Found the plugin useful on 28 Nov, 2016

    Excellent plugin, provides some very useful filters which saves me a lot of time.

    Vojta, thanks for the new mailto filter, I'm loving it! :)

  • Found the plugin useful on 12 Aug, 2016

    Great works!

    Add please this extension) https://github.com/asm89/twig-cache-extension

  • Found the plugin useful on 4 Jul, 2016

    good work

  • Found the plugin useful on 18 Apr, 2016

    Great plugin, very useful.

1.2.0

Require PHP 7.0 as minimum version.

Sep 24, 2017

1.1.3

Add sortbyfield filter to sorting arrays/fields by key.

Sep 11, 2017

1.1.2

Add strip_tags filter

Sep 11, 2017

1.1.1

Add revision filter

Aug 03, 2017

1.1.0

Make changes for Laravel 5.5.

Aug 03, 2017

1.0.15

Add DE and HU locale (thanks to Szabó Gergő and Sebastian Hilger)

Jan 09, 2017

1.0.14

Add pt-br locale for time_diff translation (thanks to Ronaldo Ribeiro de Sousa)

Jan 08, 2017

1.0.13

Make time_diff translatable.

Jan 08, 2017

1.0.12

Add mailto text parameter and rtl filter.

Dec 20, 2016

1.0.11

Add mailto filter for rendering encrypted email addresses.

Nov 28, 2016

1.0.10

Remove pre tag from var_dump

Oct 15, 2016

1.0.9

Add var_dump filter and function.

Oct 15, 2016

1.0.8

Plugin can be installed over Composer.

Oct 15, 2016

1.0.7

Add the session() and trans() helper functions (thanks to Sebastian Hilger)

Jul 12, 2016

1.0.6

Fix localizednumber and localizedcurrency filters (thanks to Vita Zoubek)

Apr 20, 2016

1.0.5

Add config function (thanks to Sebastian Hilger)

Apr 18, 2016

1.0.4

Add leftpad, rightpad and strpad filters. Cover by unit tests.

Mar 25, 2016

1.0.3

Fix uppercase, lowercase and ucfirst for UTF-8 characters

Mar 07, 2016

1.0.2

Add template_from_string function

Feb 28, 2016

1.0.1

First version of TwigExtensions

Jan 05, 2016