How to concatenate / append a string to another one in Jekyll / Liquid?

JekyllLiquid

Jekyll Problem Overview


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 %}

Jekyll Solutions


Solution 1 - Jekyll

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 %}

Solution 2 - Jekyll

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).

Solution 3 - Jekyll

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAsTeRView Question on Stackoverflow
Solution 1 - Jekylluser2490676View Answer on Stackoverflow
Solution 2 - JekyllCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 3 - JekyllLerkView Answer on Stackoverflow