I need something to replace <li>
with count index like 1,2,3 etc in Freemarker.
Here is the sample code:
<li>some text in list item one</li>
<li>some text in list item two</li>
<li>some text in list item three</li>
Expected result needs to be like below code -
1 some text in list item one
2 some text in list item two
3 some text in list item three
I've tried replace function but it will only replace all <li>
with single value.
${content?replace('<li>','-')}
To do this properly, you need a HTML parser (like JSOUP), or better yet, some library that can convert HTML to plain text. Then you have to expose that tool to templates, etc.
But, the question was, how to replace something with its ordinal. You have to write a macro for that:
<#-- Prints 1st parameter with replacements, inserting the ordinal of replacement before each. -->
<#macro printWithNumberedReplacements s replaced replacement>
<#local unprintedIdx = 0>
<#list 1..10000000 as ordinal>
<#local liIdx = s?index_of(replaced, unprintedIdx)>
<#if liIdx == -1>
${s[unprintedIdx ..]}<#t>
<#break>
<#else>
${s[unprintedIdx ..< liIdx]}${ordinal}${replacement}<#t>
<#local unprintedIdx = liIdx + replaced?length>
</#if>
</#list>
</#macro>
and then:
<@printWithNumberedReplacements content '<li>' ' '/>