Welcome to OGeek Q&A 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...