How to add a conditional elements into the title of a page? 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' }} -&gt; {{ 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 %}