81

To be clear, assuming:

{% assign my_var = "123" %}
{% assign another_var = "456" %}

I would like to append string to my_var to get something like 123 - 456

What I have tried so far:

{% assign my_var = my_var + " - " + another_var %}

3 Answers 3

153

You could use the capture logic tag:

{% capture new_var %}{{ my_var }} - {{ another_var }}{% endcapture %}

It is also possible to use the append filter, as Ciro pointed:

{% assign new_var = my_var | append: ' - ' | append: another_var %}
2
  • 1
    This is great. An important thing to stress about this answer is not to break the capture onto multiple lines as it's whitespace sensitive. If I tried to make my template more readable by doing so, I found my comparison would return false because it captures the line breaks as well.
    – Tina
    Jan 25, 2016 at 3:00
  • If you do want to break the capture onto multiple lines, then you can use {%- and -%} to strip out white spaces. shopify.github.io/liquid/basics/whitespace
    – rottweiler
    Sep 25, 2020 at 7:50
57

append: filter

This is more convenient than capture for short concatenations:

{% assign x = 'abc' %}
{% assign y = 'def' %}
{% assign z = x | append: ' - ' | append: y %}
{{ z }}

Output:

abc - def

Tested on jekyll 3.0.4 (github-pages 75).

9

All the answers so far are correct, but they fail to mention that you can also inline the append instead of having to assign a new variable:

<a href="{{ foo | append: ' - ' | append: bar }}">Link</a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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