Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>','-')}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.6k views
Welcome To Ask or Share your Answers For Others

1 Answer

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>' ' '/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...