premasagar / tim

A tiny, secure JavaScript micro-templating script.
251 stars 26 forks source link

Firefox URI-encodes Tim tags within DOM tags #9

Open kfancy opened 13 years ago

kfancy commented 13 years ago

Firefox is URI-encoding Tim tags used within DOM tags as part of the tag itself.

Examples: <a href="{{foo.link}}">{{foo.text}}</a> <img src="{{foo.img}}" />

Using Firebug, you can see that Firefox conveniently converts the tags to: <a href="%7B%7Bfoo.link%7D%7D">{{foo.text}}</a> <img src="%7B%7Bfoo.img%7D%7D" />

In short, this problem requires running the Regular Expression replace function twice if the browser is Firefox. During the second run, the tags should be encoded using encodeURIComponent() inside the regex pattern.

Fix I've implemented: I'm using Mootools, so my solution is Mootools-centric. Also, I extracted the core Tim lite functionality and rolled it into a component for my own templating system so it's not completely Tim-ready, but here's the idea:

    tim_start: '{{',
    tim_end: '}}',
    tim_path: '[A-Za-z0-9_][\\.A-Za-z0-9_]*',

    tim_tpl: function(tpl) {
        var pattern = new RegExp(this.tim_start + "\\s*("+ this.tim_path +")\\s*" + this.tim_end, "gi");

        tpl.set('html',tpl.get('html').replace(pattern, function(tag, path){
                // tag = entire {{tag}}
                return this.resolve_ref(path);
            }.bind(this)));

        if (Browser.firefox) {
            pattern = new RegExp(encodeURIComponent(this.tim_start) + "\\s*("+ this.tim_path +")\\s*" + encodeURIComponent(this.tim_end), "gi");
            tpl.set('html',tpl.get('html').replace(pattern, function(tag, path){
                    // tag = entire {{tag}}
                    return this.resolve_ref(path);
                }.bind(this)));
        }

        return tpl;
    },