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

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

javascript - Replace <li> element with replace count index in Freemarker

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...