I need to set the page title like this:

{% if entry.artistFirstName | length %}
    {{ entry.artistFirstName | capitalize }}
{% endif %}

{{ entry.title | capitalize }}

So if a first name is set I need to display it, but if not I only need to display the entry's title.

Here is one of the solutions I've tried but unfortunately does not work:

{% set title = {% if entry.artistFirstName | length %}
    {{ entry.artistFirstName | capitalize }}
{% endif %}

{{ entry.title | capitalize }} %}

It does not seem possible to define something in something that is being defined. Any idea how to get around this?


I suggested an edit to Jamies suggestion (hope that's okay - don't know all the rules yet). Here's the suggestion

{% set title = (entry.artistFirstName) ? [entry.artistFirstName, ' ', entry.title]|join : entry.title %}
{{ title | capitalize }}

Here i'm joining the two variables if entry.artistFirstName exists, by first putting all the parts into an array, and then using the join filter to glue them together. I like this approach, because it's easy to add many parts without having to put ~ ' ' ~ for every space you need.

In general, if you want to glue strings like this together, you use the ~ operator, like this:

{{ 'string1' ~ 'string2' ~ 'string3' }} -> {{ string1string2string3 }}

An alternative approach to the one I suggest above is therefore like so:

{% set title = (entry.artistFirstName) ? entry.artistFirstName ~ ' ' ~ entry.title : entry.title %}

This is just as fine, but the first approach might be nicer if you have more parts.

A third way is this, which might be just as nice/clean, but maybe slightly less readable?

{% set title = (entry.artistFirstName) ? '%s - %s'|format(entry.artistFirstName, entry.title) : entry.title %}
| improve this answer | |

How about this?

We assign the result of a conditional to a variable called title. The conditional checks if entry.artistFirstName is not empty. If true we assign it to the title variable, if false we fallback to assigning entry.title instead.

{% set title = (entry.artistFirstName) ? entry.artistFirstName ~ ' ' ~ entry.title : entry.title %}

{{ title | capitalize }}
| improve this answer | |
  • Thanks! But it seems to not work for me. If entry.artistFirstName is defined it only outputs entry.artistFirstName instead of entry.artistFirstName + entry.title. – Romain Poirier Sep 16 '14 at 20:20
  • Ok I edited my original reply. Hopefully you can work out the exact formatting you want from that. – Jamie Pittock Sep 16 '14 at 21:49
  • Thank you very much, now it works! But I validate the answer from Fred Carlsen which is more complete, and which could be useful to others in a much larger number of cases. – Romain Poirier Sep 17 '14 at 20:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.