Reputation: 119
I have a YAML file that has multiple line breaks:
key: |
some stuff
some more stuff
...
etc.
I read it into my .html file and access it. I'd like to break it up so that every time a new line is read, it creates a new paragraph:
<p>some stuff</p>
<p>some more stuff</p>
...
<p>etc.</p>
I'm trying to run it through a filter {{ key | split: '\n' }}
, but this doesn't work (it's searching for the characters \ and n instead of an actual CRLF.) I've found that passing it through an inspect
filter converts to parsable \n, but this seems like a hacky way to do this. Is there a better way?
Thanks in advance.
P.S. I believe switching my .html to .markdown might resolve this issue, but I'd rather not switch if possible because of its tendency to force me to have <p>
or <div>
even when I don't want them.
Upvotes: 2
Views: 1010
Reputation: 25157
Liquid does not convert escaped characters in strings. However, YAML has support for \n
as an escaped character in double-quoted strings. This is the same as in JSON strings, with YAML being a superset of JSON.
Both the Jekyll config file and page front matter is written in YAML.
newline: "\n"
You can add this custom variable to the context of either _config.yaml
(site.newline
), or just the individual page front matter (page.newline
). This should allow you to use split: xxxx.newline
based on either of the contexts.
My own use-case is to "cleanly" output a single linefeed character in the rendered output.
{{- site.newline -}}
While \n
counts as whitespace, you may still strip surrounding hardcoded whitespace, in particular to clean up surrounding source code indentation and line-breaks from the output.
Upvotes: 0
Reputation: 52829
\n
is a regexp linefeed character class. Sadly, liquid doesn't know this.
But we can create one thing that liquid will understand : a real linefeed.
This is the trick :
# _config.yml
newline: >
:
{{ site.newline | inspect }}
now contains ":\n" with a real line feed in it.
Note that the colon is here to preserve the linefeed during front matter parsing. It can be replaced by any other char, but it's required.
The complete tag is {% assign newline = site.newline | remove: ":" %}
. We now have a clean linefeed in our var.
We can now split our multi-lines var with {% assign keyArray = page.key | split: newline %}
, and we get {{ keyArray | inspect }} output>> ["some stuff", "some more stuff", "...", "etc."]
.
Upvotes: 1