问题描述:

I'm making my first Meteor app - a regular expression matcher is the first component that I'm making. It will highlight matching items in an editable string by surrounding the matches with a span tag.

I figured out how to create the tags around matches in vanilla JavaScript:

http://jsbin.com/iXUVUJA/1/

But the way I added it into a Meteor template, the tags are being shown in the browser. Is there a way to have the tags read as html in the browser?

Here is the relevant code from my .js file:

var str = "There are thousands and thousands of uses for corn... All of which I will tell you about right now.";

var regEx = /[A-Z]/g;

if (Meteor.isClient) {

Template.sampleText.someText = function() {

return str.replace(regEx, ("span class='highlighted'>" + "$&" + "</span>") );

};

}

And here is the relevant code from my .html file:

<template name="sampleText">

{{someText}}

</template>

This is the output on the page from the server:

span class='highlighted'>There are thousands and thousands of uses for corn... span class='highlighted'>All of which span class='highlighted'>I will tell you about right now.

网友答案:

You can use Handlebars.SafeString, as seen in the Handlebars documentation. In your case you can do:

if (Meteor.isClient) {
  Template.sampleText.someText = function() {
    var element = str.replace(regEx, ("span class='highlighted'>" + "$&" + "</span>") );
    return new Handlebars.SafeString(element);
  };
}
相关阅读:
Top