Search code examples
eleventy

Data files with html content


I'm making a nice simple html page using external data... here's the bit that's causing me grief:

<section class="faq_main">
{% for section in faq.sections %}
    <h3>{{ section.heading }}</h3>
    {% for question in section.questions %}
        <article class="faq_question">
            <a id="hide_{{ section.code }}_{{ question.code }}"
               href="#hide_{{ section.code }}_{{ question.code }}"
               class="hide"><span class="faq_toggler">+</span> {{ question.question }}</a>
            <a id="show_{{ section.code }}_{{ question.code }}"
               href="#show_{{ section.code }}_{{ question.code }}"
               class="show"><span class="faq_toggler">-</span> {{ question.question }}</a>
            <div class="details">
                {{ question.answer }}
            </div>
        </article>
    {% endfor %}
    <p>&nbsp;</p>
{% endfor %}
</section>

... and the matching faq.json file:

{
    "sections" : [
      { "heading" : "Section the first",
        "code" : "gn",
        "questions" : [
                {
                    "question": "What do questions need?",
                    "code" : "1",
                    "answer": "An answer"
                },
                {
                    "question": "Is this also a question?",
                    "code" : "2",
                    "answer": "Yes, it is"
                },
                {
                    "question": "Is this junk data?",
                    "code" : "a",
                    "answer": "Yes"
                },
            ]
        },
        {
            "heading": "Another section",
            "code" : "f",
            "questions": [
                {
                    "question": "Can I have html in my answer?",
                    "code" : "2",
                    "answer": "<ul>\n<li>First, json needs newlines escaped to be newlines</li>\\n<li>Eleventy seems to 'sanitize' the string</li>\\n</ul>"
                },
                {
                    "question": "question b",
                    "code" : "b",
                    "answer": "answer b"
                },
                {
                    "question": "question c",
                    "code" : "or",
                    "answer": "answer c"
                },
            ]
        }
    ]
}

.... and the rendered text for the answer in question is:

<ul> <li>First, json needs newlines escaped to be newlines</li>\n<li>Eleventy seems to 'sanitize' the string</li></ul>

Do I have any options here? Is there a way to allow [even a subset of] html elements into the page?

(and yes, the CSS does the clever show/hide descriptions using the '+'/'-' symbols - all that side of things works just lovely)


Solution

  • Change {{ question.answer }} to {{ question.answer | safe }}

    (see https://www.11ty.dev/docs/layouts/#prevent-double-escaping-in-layouts - it's clear, once you understand what it's saying :) )