1

Building on this question here: Create line breaks from text field

What approach would be best for breaking a multi line plain text field into multiple single lines to be used as:

<span>{{ textfield.lineOne }}</span>
<span>{{ textfield.lineTwo }}</span>
<span>{{ textfield.lineThree }}</span>

At the moment, my approach is to use a Matrix for the user to be able to add individual lines, but I'd much rather I was able to present the client with a multiline text field and rework them in the template.

2
{% set text %}
    Here is some
    Text that spans
    multiple lines
{% endset %}

{% set textArray = text | split('\n') | filter %}

{% for line in textArray %}
    <span>{{ line }}</span>
{% endfor %}
  • Brilliant. Exactlay what I needed! Cheers, Trevor. 👍🏼 – Jay Aug 22 '18 at 18:23
2

I've made a little macro for this:

{% macro splitText(text) %}
  {% set text = text|nl2br|raw %}
  {% set text = '<span class="split_text">' ~ text|replace('<br />', '</span> <span class="split_text">') ~ '</span>' %}
  {{ text|raw }}
{% endmacro %}

You may need to tweak it a bit, but this is what worked for me.

  • Perfectly good answer. Ended up going with Trevor's below because I liked the control of the forloop. Gave me access to 'loop.index' in there, too. Thanks though, Will! – Jay Aug 22 '18 at 18:23
  • 1
    Makes sense to me. I like that solution better, too :) – Will Browar Aug 22 '18 at 19:27

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.