Search code examples
javascriptjqueryjquery-templates

Using jquery-template {{wrap}} to wrap plain text


With jQuery templates, I'm trying to use the {{wrap}} template tag to wrap the results of another template. This second template renders plain text, not HTML. I currently get an empty string where I expect to get the plain text rendered by the wrapped template.

If I surround the plain text with some HTML elements, like a <div> tag, then everything works fine, but I get the <div> rendered into the results. I would be fine creating a dummy tag around my contents in order to get the {{html}} tag to work, but I wouldn't want it in the rendered results.

I will also want to use this same wrapper, if possible to wrap templates that actually do produce HTML as well, so it would be good if the same wrapper template can work for both cases.

Here is my code:

$("#x").html($("#myTmpl").tmpl());

<div id="x" />
<script id="myTmpl" type="text/x-jquery-tmpl">
  The following wraps some non-HTML content: {{wrap "#wrapper"}} help {{/wrap}}
</script>

<script id="wrapper" type="text/x-jquery-tmpl">
  <table>
    <tbody>
      <tr>
        <td>
          Wrapped content: {{html $item.html}}
        </td>
      </tr>
    </tbody>
  </table>
</script>

This code can be found at this jsFiddle: http://jsfiddle.net/bernardchen1/BYdeg/


Solution

  • I eventually found a solution. I created use a dummy tag to wrap the plain text (or even the html that is produced by other templates), and then I created a function that I pass into the template invocation that can strip out the dummy tag. I invoke it like this: {{html $data.clean($item)}}. The "clean" function needs access to the content being returned by the inner template, which I found to be $item.wrapped[0]. Once I had that content, I could get its inner html to return from the clean function.

    I'm concerned about whether I'm supposed to be accessing $item.wrapped though.

    Ultimately, I may just try refactoring my code to not require this dummy tag and the cleaning function.

    This solution can be found here: http://jsfiddle.net/bernardchen1/nmzWt/

    Edit: there is another solution to call appendTo to attach the template html to another DOM element, and then grab the data back out.