Search code examples
javahtmlspringspring-bootfreemarker

How to parse String HTML with Freemarker variables


I am retrieving a String value from the database which contains a mix of HTML and Freemarker syntax.

Like so:

<p>${fragment.title}</p>
<table id='resultsTable' class='material-table'>
    <tr>
        <th>Instruction</th>
        <th>Action</th>
    </tr>
Test
</table>

The following is how I access the above String in the Freemarker template:

<#include "inc/header.ftl">
<body>
<#include "inc/navigation.ftl">
<div class="container">
    <div class="row">
        <#if fragments??>
            <#list fragments as fragment>
                <div class="col-sm-6">
                    <div class="fragment">
                        ${fragment.design?html}
                    </div>
                </div>              
            </#list>
        </#if>
    </div>
</div>
</body>
<#include "inc/footer.ftl">

But the output is not quite right:

<p>${fragment.title}</p> <table id='resultsTable' class='material-table'> <tr> struction</th> </th> </tr> ddd </table>

How do I use Freemarker to parse the HTML and parse the value of ${fragment.title} at the same time?


Solution

  • Instead of ${fragment.design?html}, use <@fragment.design?interpret />.

    Related documentation:

    Note that if you need to run a lot of ?interpret-s per second, and you tend to interpret the same strings again and again in your templates, you might need some custom solution that caches and reuses the Template-s made from those strings. But, in most applications, performance is not an issue with ?interpret.

    BTW, you don't need that #if fragments?? if you use <#list fragments! as fragment> (note the !).