0

I use the templates and javascript to generate the htmls for an json data, this is the tempalte:

    <div id="template">
        <div class="iwContainer">
            <div class="iwHeaderContainer">
                <div class="iw-title-container">
                    <span class="titleText">${name}</span> <a target="_blank" href="detail?fid=${id}" class="titleLink">Detail</a>
                </div>
            </div>
            <div class="iwRichContainer">
                <div class="iw-g-font">Address:${address}</div>
            </div>
            @{setsearchTemplate}
        </div>
    </div>

Js:

buildInfoContent : function(item) {
    var tmp = $("#template").html();
    if (tmp) {
        tmp = tmp.replace(/\$\{(\w*)\}/g, function(m, key) {
            return item.hasOwnProperty(key) ? item[key] : "";
        });
        return tmp;
    }
}

And I call it:

buildInfoContent({name:'name',id:2,address:'address'});

And all of the palcehodler are replaced but the ${id}.

Through firebug I found that the temlate is something like this:

.........<span class="titleText">${name}</span> <a target="_blank" href="detail?fid=$%7bid%7d" class="titleLink">Detail</a>.......

So the id is not replaced, how to fixe it?

3
  • 2
    It runs fine for me: jsfiddle.net/QH8gG Commented Jun 7, 2013 at 2:24
  • :(. I test no another machine, it works, but not on my own machine. Commented Jun 7, 2013 at 2:42
  • So, any idea to change the { } to other character? Commented Jun 7, 2013 at 2:42

1 Answer 1

1

It looks like your browser is encoding your {} characters. You'll have to account for that in your regexp...

This is untested but... /\$(\{|%7b)(\w*)(\}|%7d)/

This should do it, or something very similar...The idea is their though. Sometimes browsers do funky things with special characters.

EDIT: To match the key (the middle matched group), try using the 3rd argument passed to your callback, like in this example : Fiddle

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, I use your regexp and I use this function :function(m, key) {key=RegExp.$2; return item.hasOwnProperty(key) ? item[key] : ""; } I wonder if this contains any potential problems?
You should be able to just copy the regex above over the current regex youre using, you shouldn't have to change any other code.
No, without change other code, the key will be { not the property name.
I gotcha you are right, you want the second matched group of the 3.
I am goint to be crazy, the Regexp.$2 return empty in IE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.