admin管理员组

文章数量:1404927

I have situation where I have to append the String to the variable in the freemarker template.

for example:

I have have list of objects and each returning specific values so that I can store these values in freemarker declare object and passed it to javascript function later in the template.

here is some code snippet:

// This is the list of items
[#list itemsList as item]

//here I am getting the object that I wanted to add in the template object
[#object = item.getObject()!]

//This is how I would like to append the object
[# itemsToAppendTo = "<div class="subs" id="til2"" + ${object} + "</div>"

[/#list]

//finally once loop finishes I would like to send the object to javascript

<script>

 // A $( document ).ready() block.
$( document ).ready(function() {

  var html = ${itemsToAppendTo}

  $('.gTA').append( html ) 

});  

Also, please provide suggestion if there is any better way to acplish this task.

I have situation where I have to append the String to the variable in the freemarker template.

for example:

I have have list of objects and each returning specific values so that I can store these values in freemarker declare object and passed it to javascript function later in the template.

here is some code snippet:

// This is the list of items
[#list itemsList as item]

//here I am getting the object that I wanted to add in the template object
[#object = item.getObject()!]

//This is how I would like to append the object
[# itemsToAppendTo = "<div class="subs" id="til2"" + ${object} + "</div>"

[/#list]

//finally once loop finishes I would like to send the object to javascript

<script>

 // A $( document ).ready() block.
$( document ).ready(function() {

  var html = ${itemsToAppendTo}

  $('.gTA').append( html ) 

});  

Also, please provide suggestion if there is any better way to acplish this task.

Share Improve this question asked Aug 19, 2017 at 13:14 OmerOmer 5441 gold badge7 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

Just generate the output as usual, capture it into a variable (html), then print it into the JavaScript part.

<#assign html>
  <#list items as item>
    <div ...>${item.object}</div>
  </#list>
</#assign>
...
<#-- Attention: Remove ?markup_string if you aren't using any output format! -->
var html = "${html?markup_string?js_string}";

?markup_string is only needed if you are using HTML/XML/XHTML output format (or any other markup output format). If you aren't using any, it will fail saying that the left-hand operand was a string, so you will know.

The ?js_string ensures that quotation marks and such will be escaped with backslash.

Note that you can also append to a string like this:

<#assign s = 'foo'>
<#assign s += 'bar'>
${s} <#-- foobar -->

but it's less practical I guess (and slower if you append for many times).

本文标签: javascriptHow to append String in freemarker templateStack Overflow