Preparse Field


A fieldtype that parses Twig when an element is saved, and saves the result as plain text.


Usage

When creating a new Preparse field, you can add the Twig that you want to run to the fields settings. When an element with a preparse field is saved, the code will be parsed. The element itself is available as element in twig.

Usage in Matrix
When a Preparse field is added to a Matrix block, that block will be available to the Twig code as the variable element. The element that the Matrix field belongs to will be available under element.owner.

Examples

If you have a category field in your entry named entryCategory, you can save the category title to the preparse field by adding the following Twig to the field settings:

{{ element.entryCategory | length ? element.entryCategory.first().title }}

This is useful for saving preparsed values to a field for use with sorting, searching or similar things.

You can also do more advanced stuff, for instance for performance optimizing. Let's say you have three different asset fields that may or may not be populated. having to check these in the template may require a bunch of queries since you can't check if a field has a relation in Craft, without actually querying for it. You could do something like this to get the id of the asset to use:

{% if element.smallListImage | length %}
    {{ element.smallListImage.first().id }}
{% elseif element.largeListImage | length %}
    {{ element.largeListImage.first().id }}
{% elseif element.mainImage | length %}
    {{ element.mainImage.first().id }}
{% endif  %}

You'd probably want to wrap that in {% spaceless %} ... {% endspaceless %} to make it more useful.

Or you could just use it to do some bulk work when saving, like pre-generating a bunch of image transforms with Imager:

{% if element.image | length %}
    {% set transformedImages = craft.imager.transformImage(element.image.first(), [
	    { width: 1000 },
	    { width: 900 },
	    { width: 800 },
	    { width: 700 },
	    { width: 600 },
	    { width: 500 },
	    { width: 400 },
	    { width: 300 },
	    { width: 200 },
	    { width: 100 }
    ]) %}
{% endif %}

The template path is set to your site template path, so you can even include whole templates if you want to do more advanced stuff and/or want to keep your fields Twig in version control:

{% include '_fields/myFieldInclude' %}

Make sure that you always write solid Twig, taking into account that fields may not be populated yet. If an error occurs in your Twig, the element will not be saved.


Free

Package Name

To install this plugin, search for its package name on the Plugin Store and click “Install”.


Information

  • Version 1.2.1
  • Last Update 6/25/2020
  • Active Installs 1,445
  • Compatibility Craft 3
  • License MIT
  • Categories Performance, Fields

Report an issue