2

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.

Jay
  • 1,042
  • 7
  • 24

2 Answers2

3
{% 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 %}
Trevor Davis
  • 588
  • 2
  • 14
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.

Will Browar
  • 101
  • 1
  • 10
  • 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