Can't run html on text string in JQuery tmpl
Asked Answered
M

2

5

In a JQuery template in my project, I am trying to write out a variable which is an HTML string without encoding the HTML. When I just output the variable like so:

 ${description}

it results in the raw HTML string being outputted with tags and all like so:

<p>text <b>bold</b>  <i>italic</i></p>

But when I try to turn the markup into real tags at the same exact place in the code:

   {{html $description}}

doesn't output anything!

I tried a zillion ways of passing in the variable, but I think there's something going on in the html routine I'm not getting.

Thanks.

Update:

Here's how it's being called:

    this.$el.attr('data-id', tmplData.id).
          data('id', tmplData.id).html($.tmpl(this.template, tmplData));

Where this.template is the template file and tmplData is JSON which includes $description and the other variables needed.

Another update:

 {{html '<p>string</p>'}}

does behave as expected. But

 {{html $another_variable}}

fails to produce any output even when $another_variable doesn't have an HTML in it.

Another update:

I also tried:

 ${$item.html(description)}

and changed the call to the template to

 this.$el.attr('data-id', tmplData.id).
         data('id', tmplData.id).
         html($.tmpl(this.template, tmplData, {
            truncate: _.truncateStrip,
            html: _.html,
        }));

And wrote a custom html routine to pass through the string unchanged as was recommended:

 html: function(str) {
        return str;
    }

but still no dice.

Marchpast answered 7/2, 2013 at 1:1 Comment(0)
M
15

The answer is:

{{html description}}

I tried that early on, but because I left stray spaces inside the curly brackets, it did not interpret properly.

:-(

Marchpast answered 7/2, 2013 at 2:13 Comment(2)
Thanks, mine didn't work at first, because I still had the dollar sign in front.Sore
That's the best and most proper answer by far, far, far. ThanksSleet
W
0

If you open the source you can modify the line that does the encoding. I didn't see an option to turn it off so this might be the easiest solution for you.

Change:

encode: function( text ) {
            // Do HTML encoding replacing < > & and ' and " by corresponding entities.
            return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
        }

to

encode: function( text ) {
            // Do HTML encoding replacing < > & and ' and " by corresponding entities.
            return text;        
}
Wartime answered 7/2, 2013 at 1:26 Comment(1)
I didn't want to make a global change, but see the last edit above -- I tried something like what you recommended, but it made no difference.Marchpast

© 2022 - 2024 — McMap. All rights reserved.