Twig for MODX: new templating extra for MODX 3

Ever written a snippet whose only job is to loop over a list? Or stared at a chain of output modifiers trying to figure out which one handles the “empty” case?

Twig for MODX adds if/else, for loops, and filters to your MODX templates. If you’ve used Symfony, Craft, or Drupal, you already know the syntax. If you haven’t, here’s what it looks like:

<h1>{{ resource.pagetitle }}</h1>
{% if resource.MyImageTV %}
    <img src="{{ resource.MyImageTV }}">
{% endif %}
{{ chunk('HeroCta', {label: 'Buy now'}) }}

Resource fields and TVs work the same way – {{ resource.pagetitle }} and {{ resource.MyCustomTV }} are both just properties on resource.

Twig renders before MODX tags (and Fenom template tags), so {{ myvar }} and [[+myvar]] work side by side in the same template. Or chunk. You can try it on one page and leave everything else alone. If you use pdoTools or Fenom, those keep working too – Twig’s double-brace syntax won’t collide with any of it.

All HTML output is escaped by default, so you get XSS protection without thinking about it. There are built-in functions for the MODX features you already use: chunk(), snippet(), option(), lexicon(), link().

And if you use ContentBlocks, Twig works inside its templates and repeaters. Yes, now you can loop over repeated fields in a single template.


Now for the practical bit

Start with the documentation site (including “How To’s” and guides) then install it from the Extras directory (or grab the latest release from GitHub) and try it on your site. If you have any problems, head to the GitHub repository and open an issue or start a discussion.

3 Likes

Thank you so much for sharing this @pbowyer! It looks great, and it’s very helpful to have such good documentation from the outset. I will test it in a new project over the next few weeks, and then I will get back to you with feedback and, if needed, pull requests. Thank you!

Look forward to it @jenswittmann!

The developer experience when using Twig for MODX inside ContentBlocks is weaker than I would like, because I’ve chosen to expose the raw data. So you have to append .value to get the field values e.g.

{% for r in row_data %}
        <div class="bo__panel{{ loop.first ? ' active' : '' }}">
            <h3 class="bo__panel-title">{{ r.name.value }}</h3>
            <div class="bo__items">
{{ r.content.value | raw }}
            </div>
        </div>
{% endfor %}

If you use ContentBlocks with MODX it’d be great to get your feedback on what would feel good to use.

1 Like

As some fields have multiple values, that’s actually great and makes sure all information is available for templating. :+1:

1 Like