Skip to content

Making twig do things it really shouldn't. while, break, continue, and return tags plus tests, operators, and filters that probably don't belong in the language

License

Notifications You must be signed in to change notification settings

marionnewlevant/craft-twig_perversion

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Twig Perversion plugin for Craft CMS

Making twig do things it really shouldn't. Twig is not intended to be a general purpose programming language, and there are some things that really don't belong in the language. This plugin adds a few of those things anyway.

  • {% break %}, {% continue %}, and {% return %} tags
  • is numeric test
  • json_decode filter

Installation

  1. Install with Composer via composer require marionnewlevant/twig-perversion from your project directory
  2. Install plugin in the Craft Control Panel under Settings > Plugins

Using Twig Perversion

Tags

{% break %} to exit a for loop:

{% for straw in haystack %}
  {% if straw == needle %}
    {% break %}
  {% endif %}
{% endfor %}

{% continue %} to continue to next iteration:

{% for straw in haystack %}
  {% if not isInteresting(straw) %}
    {% continue %}
  {% endif %}
  {# do whatever... #}
{% endfor %}

{% return value %} to return a value from a macro:

{% macro foo() %}
  {# ... calculate someValue ... #}
  {% return someValue %}
{% endmacro %}

{% return %} to return the empty string form a macro:

{% macro foo() %}
  {# ... do stuff %}
  {% return %}
{% endmacro %}

A macro with a {% return %} tag will return whatever the return value is (which can be a complex expression). Any other output generated by the macro will be discarded.

Tests

  • Numeric Test whether given value is numeric (behaviour like PHP 7 is_numeric). (Note that as of PHP 7, hexadecimal strings are not considered numeric)

Examples

{{ 12 is numeric ? 'Yes' : 'No' }}
{# Yes #}

{{ '-1.3' is numeric ? 'Yes' : 'No' }}
{# Yes #}

{{ '0x539' is numeric ? 'Yes' : 'No'}}
{# No #}

Filters

  • json_decode Decode json string, returning php associative arrays. Uses the PHP json_decode function

Brought to you by Marion Newlevant

About

Making twig do things it really shouldn't. while, break, continue, and return tags plus tests, operators, and filters that probably don't belong in the language

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •