18

If you‘ve got a multi-lingual site (or even if you don’t), you can pass variables into strings with the |t filter: {{ "Welcome back, {name}"|t( {'name': currentUser.name} ) }} (See http://buildwithcraft.com/help/static-translations for details on how you can use the |t filter to translate your text.)


16

I know three ways: Using format() (look for type specifiers) {% set string = "There is an %s."|format("apple") %} Using string interpolation (assuming that apple="apple") {% set string = "There is an #{apple}." %} Using string concatenation (assuming that apple="apple") {% set string = "There is an " ~ apple %}


13

You can get the current template’s name like so: {{ _self.getTemplateName() }}


12

To my knowledge this is not possible natively in Twig. Depending on your situation / template needs here are some useful tests {% if foo is iterable %} Array or object {% if foo is same as(true) %} Basically identical to using === in php


12

I've had luck using "is defined" before using other logic operators. This should do it: {% if entry.title is defined and entry.title | length == 0 %} {% set entry = craft.entries.section('sectionname').slug(craft.request.segment(2)).first() %} {% endif %}


12

It should be a string: {% for entry in craft.entries({ section: 'news', limit: 2, id: 'not 42' }) %} so concat your variable like so: {% for entry in craft.entries({ section: 'news', limit: 2, id: 'not ' ~ this_id }) %}


12

I think the issue with trying to set a variable in a macro is that the variable is limited to the scope of the macro you are triggering, so {% set parent = thisEntry %} is available within the scope of your macro, but doesn't define it for the rest of your template. Macros are comparable with functions in regular programming languages. They are useful to ...


11

You can leave the with lightswitchTest part off altogether, and all the variables from the parent template will be available inside the include too. with expects an array, where the keys correspond to the variable names and their values, so if you did want to explicitly pass that in (say as a different variable) you could use: page.twig {% include "...


10

If I understood your question correctly then you should be able to do it as follows: {% set sizes = [] %} {% for productAttribute in entry.productAttributes %} {% set sizes = sizes|merge([productAttribute.size]) %} {% endfor %} {% set sizes = sizes|join('|') %} The sizes variable will then be a string containing the pipeline separated sizes, for ...


10

You'll never need to put Twig tags within other Twig tags... Try it like this: {% include "partials/includes/page-header" with { 'title' : entry.heading } %}


10

Solution: return craft()->config->get('environmentVariables')['baseUrl'];


9

Another option is to use the twig join filter: {% set urlParam = [street, city, 'UT']|join(', ') %} join concatenates the items in the sequence with the separator of your choice in between.


9

A little bit late but maybe someone else has the same issue and want's to accomplish this. You can use this Plugin Twig Perversion to create macros that return values {% macro getParentEntry(thisEntry) %} {% import _self as self %} {% if thisEntry.parent|length %} {% set parent = thisEntry.parent %} {% else %} {% set parent = ...


8

Figured it out! Proper syntax is: {% set urlParam = street ~", " ~city ~", UT" %}


8

I found the answer in the Twig documentation: http://twig.sensiolabs.org/doc/templates.html#variables You can use a dot (.) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array), or the so-called "subscript" syntax ([]): {{ foo.bar }} {{ foo['bar'] }} When using the subscript syntax, you can concatenate the ...


7

I needed this feature today, so I've put together a simple plugin, which does the job: Craft-TwigTypeTest Example: {% set test_var = craft.entries %} {% if test_var is of_type('object') %} true {% endif %} or {% set test_var = craft.entries %} {{ test_var|get_type }} {# Outputs: object #}


7

I recently needed to check if a variable is a number. My first idea was to use the divisibleby test: {# DOESN'T WORK AS EXPECTED! #} {% if var is divisible by(1) %} {% endif %} Unfurtunatelly twig returns true for every string passed to it. But what you can do is to use regular expressions using the matches operator in the comparison. You'll note that I ...


7

They're both the same for the most part. The only time I'd use the second way you listed is when the property is a variable. For instance: {% set foo = 'name' %} {{ variable[foo] }} This will give you {{ variable.name }}


7

In Craft 3, {{ _self.getTemplateName() }} throws an error, but {{ _self }} does the trick.


7

Edit: I needed to do a little digging. Internally, Craft can actually have multiple instances of Twig_Environment running (a Twig_Environment instance is what you get back by calling craft()->templates->getTwig()). Craft caches each instance in a private class variable, with the template loader classname and a hash of the environment's options making ...


6

The error you're encountering is part of how Pixel & Tonic wrote the cache tag. In short, variables will not work for what you're trying to accomplish. For the longer explanation... Tags in Twig are made up of tokens. So strings, numbers, variables, functions, tags, and filters are all tokens. When Twig is parsing a tag, it reads all the tokens and ...


6

You're options are: Adding it as a parameter in the querystring (e.g. domain.com?key1=value1) Submitting it though a form and grabbing the value from POST. Setting the value in a cookie and retrieving it on the next page using something like this plugin. Writing a plugin with a Twig function that wraps Craft's craft()->userSession->setFlash() method, ...


6

I think the best way to do this would be in your PluginHandleVariable file's method, just have it accept one, optional parameter and expect it to be an array. public function variableMethod($options = null) { if (!$options || !is_array($options)) { return "No options set"; } // Now you can check for individual options on the array ...


6

Within your variables class file you will want to define methods that 'return' values to your template, like so: class HelloVariable { public function message() { return "Hello, world!"; } } Which you would call from your template using: {{ craft.hello.message }} On a side note, a really good place to start plugin development is to ...


6

You're exactly right: The advantage of using the variable is that you can re-use it throughout your template, which helps keep things DRY. When you use craft.entries in your template, Craft serves up an ElementCriteriaModel — This is an object that knows how to query the system for a set of entries... but it doesn't actually perform that query until you ...


5

If you want to set entry to a new value if entry.title is undefined or 0 length, try this: {% if !(entry is defined and entry.title is defined and entry.title|length) %} {% set entry = craft.entries.section('sectionname').slug(craft.request.segment(2)).first() %} {% endif %}


5

Not sure if you saw this, but you may also be able to use the Twig attribute function: {{ attribute(array, item) }} Pretty straightforward, here's the official docs page...


5

I don't believe this is currently possible outside of the context of a Craft plugin. Inside of a plugin, you could probably do it through a Twig extension so that you have access to the template instance, where you could call $template->getTemplateName(), which is part of Twig's Twig_Template abstract class.


5

In Twig, the date_modify filter returns a DateTime object. Also, date is not just a filter, but also a function. The date function accepts any a DateTime object or a string in a supported format, and returns a DateTime object. Example: {{ date("+2 years") }} This should give you a DateTime object set for 2 years from when it's triggered. Why is localeTime ...


5

You could combine the first three: {% if entry is defined and entry and entry.isEditable %} If the first or second part of this logic fails, it will not check the third part so no error will be thrown. The second part is for the rare cases that a variable with the name entry exists but is null. If entry is defined, it's always an entry (or at least it ...


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