Skip to main content
14 votes

The Definitive Guide to Extending Twig in Craft CMS

To encourage input, this is a community wiki post. Any user with at least 100 reputation points may contribute. Functions, filters, objects, macros and statements – when to use which A function is ...
7 votes
Accepted

Register multiple TwigExtensions in one plugin in Craft 3

There are several things going on here. This will be a general answer that can hopefully help you move forward. This example will use Sprout Active as a reference and you can see the code here for an ...
Ben Parizek's user avatar
  • 13.5k
5 votes
Accepted

How to access HTML input values from Twig and vice versa

You can do it without JavaScript (if you don't mind the page refreshing) by accessing the request variable: https://docs.craftcms.com/api/v3/craft-web-twig-variables-request.html#public-methods {{ ...
missmatsuko's user avatar
5 votes
Accepted

.first() vs. .one() in craft 3

.all() returns a collection of elements, which you can loop through with a for loop. .one() returns a single element, so you cannot use a for loop to access it. In this case you should just store ...
Jeremy Gimbel's user avatar
4 votes
Accepted

How to get a list item <li> using a plain text field every time I hit enter

You'll want to split on the line breaks, then loop through the resulting array... {% for ingredient in listOfIngredients|trim|split('\n') %} <li>{{ ingredient }}</li> {% endfor %}
Lindsey D's user avatar
  • 24.1k
4 votes
Accepted

Craft or Twig converting html tags to alt characters

You need to make sure that you're returning the raw version of the HTML. In Craft 2, it looks like this... return TemplateHelper::getRaw($result); In Craft 3, it looks like this... return Template:...
Lindsey D's user avatar
  • 24.1k
4 votes

How to create Twig extension in Craft CMS 5

There's a page in the docs you might have missed that covers this here: https://craftcms.com/docs/5.x/extend/extending-twig.html So specifically, you want to bind the EVENT_INIT event of the Craft ...
James Smith's user avatar
  • 5,689
3 votes

How to access HTML input values from Twig and vice versa

Twig (at least within the context of Craft) doesn't work this way I'm afraid. The Twig template is processed on the server and HTML is returned to the browser. You're trying to change the Twig based ...
foamcow's user avatar
  • 2,029
3 votes

Is it possible to extend twig with 'Twig_SimpleTest'?

Thanks Brad, that's what I was after. In the case of what I was trying to achieve; the following in my plugins init function did the job: $twig = craft()->templates->getTwig(); $twig->...
Mark Notton's user avatar
  • 2,347
3 votes
Accepted

Is it possible to extend twig with 'Twig_SimpleTest'?

When you call Craft's TemplatesService->getTwig() (craft()->templates->getTwig()), you get an instance of the Twig environment and from there you could be able to call addTest. 100% untested, ...
Brad Bell's user avatar
  • 67.6k
3 votes
Accepted

PHP eval filter for Twig

In Craft 3 it is actually possible. {{ craft.app.view.evaluateDynamicContent('phpinfo();') }} See: Can we use PHP in our templates instead of Twig?
KSPR's user avatar
  • 3,788
3 votes
Accepted

How can I validate that I am passing an Asset into my custom twig filter?

Actually, you had your code just right imo: use craft\elements\Asset; ... if (!$asset instanceof Asset) { return false; }
andrew.welch's user avatar
  • 11.6k
3 votes

Is there any way to create twig extension without a plugin?

Short answer: No. Longer answer: Sorry, no... but there's a good reason for that. Twig is a template language. PHP is business logic. In proper application design, you separate the business logic from ...
RitterKnight's user avatar
  • 6,582
3 votes

how to create a custom plugin if the user enables plugin settings then it will replace the website home page to my custom design?

I would think that you could hook into one of the template render events like: craft\web\View::EVENT_BEFORE_RENDER craft\web\View::EVENT_BEFORE_RENDER_TEMPLATE craft\web\View::...
stevecomrie's user avatar
2 votes
Accepted

How do I print a value from Craft/Twig into a Javascript function?

That is the correct way of doing it but you need to be sure that entry is a variable and set to an entry model at that point. And that you're in an appropriate part of your template in general for ...
Jeremy Daalder's user avatar
2 votes

How can I validate that I am passing an Asset into my custom twig filter?

Assuming you're using Craft 3, this should work: if (\get_class($asset) !== 'craft\elements\Asset) { return false; }
Mats Mikkel Rummelhoff's user avatar
2 votes
Accepted

Craft 3 - Fixing deprecation errors

Yes, with the launch of Craft 3, Pixel and Tonic have provided some documentation on switching from Craft 2 syntax to Craft 3.
Jamie Wade's user avatar
  • 3,644
2 votes
Accepted

Output raw html from if statement and combining strings?

{# set test variable, to make your code work #} {% set block = {imageWidth: 300} %} {# the real output #} <img{{ block.imageWidth|length ? (' width="' ~ block.imageWidth~ 'px"')|raw }} /> ...
Robin Schambach's user avatar
2 votes
Accepted

How to strip out src="" value with twig from iframe code

You could write a module that adds a twig extension to return the value of src from the string. That way you get to utilise PHP as per https://stackoverflow.com/questions/17017684/how-to-get-url-from-...
mijewe's user avatar
  • 336
2 votes

Twig json_decode gives Syntax Error

After some local experimentation I managed to reproduce and (hopefully) resolve. Like Brad said the macro returns a Markup class that is not json decodable. So first step is to use the raw filter to ...
Matanya's user avatar
  • 492
2 votes
Accepted

Craft 3 CMS How to get all Channel Names/Titles

This kind of solved my problem: {% for section in craft.app.sections.allSections %} {% if section.type == 'channel' %} {% set navBarLinks = navBarLinks|merge([section]) %} {% endif %} ...
ves's user avatar
  • 117
2 votes

Uppercase certain words in string

First, are you sure you're going about this the best way? Are the uppercase words really mixed into unformatted / free-form text so much that you can only use string replacement? Sounds like a weird ...
MoritzLost's user avatar
  • 11.9k
2 votes

How to create Twig extension in Craft CMS 5

If you started this project with a Craft 5, you have access to Generator, which can scaffold a Twig extension for you! In the project directory, run: php craft make module # ... php craft make twig-...
August Miller's user avatar
1 vote
Accepted

How to display controller response on twig template?

Your controller looks ok, though I would clean it up a bit and use more expressive variable names to reduce the surface area for bugs: $templateVariables = [ 'status' => true, 'message' =&...
MoritzLost's user avatar
  • 11.9k
1 vote
Accepted

Custom field plugin: Unable to find template / General custom field plugin information

Where are you storing your mapElement template? - Unless it is stored in the same folder as the templates for the front end of your site, then Craft::$app->getView()->setTemplateMode(View::...
Nick's user avatar
  • 146
1 vote
Accepted

TwigExtension added to Craft don’t work in emails

Replace my if condition by if ( Craft::$app->request->getIsSiteRequest() || Craft::$app->getRequest()->getIsCpRequest() ) { Thanks to Luke Holder for pushing in the right direction!
Maxime Lafrenière's user avatar
1 vote

TwigExtension added to Craft don’t work in emails

All you should need to do is remove this condition check: if (Craft::$app->request->getIsSiteRequest()) { You are only registering the twig extension for front end (site) requests, but emails ...
Luke Holder's user avatar
  • 6,897
1 vote

UnexpectedValueException after loading plugin

The solution was to replace all references to "reference":null with "reference":"" in /craft/vendor/composer/installed.json.
Tyssen's user avatar
  • 665
1 vote

Is there any way to create twig extension without a plugin?

I don’t believe there’s a way to create an actual Twig extension without making a plugin. However, depending on what you’re wanting your extension to do, would a Twig macro work? If you change your ...
Tim Knight's user avatar
  • 1,022

Only top scored, non community-wiki answers of a minimum length are eligible