How to change the default delimiter of Handlebars.js?

前端 未结 8 1867
半阙折子戏
半阙折子戏 2020-12-10 02:41

I need to use handlebars.js and I also use Blade template engine from Laravel (PHP Framework). The tags {{}} conflict with blade\'s placeholders that are exactly the same.

8条回答
  •  清歌不尽
    2020-12-10 02:51

    I used and updated the source code of user1875109 and now it works with Handlebars v3.0.3:

    /**
    * change the delimiter tags of Handlebars
    * @author Francesco Delacqua
    * @param string start a single character for the starting delimiter tag
    * @param string end a single character for the ending delimiter tag
    */
    Handlebars.setDelimiter = function(start,end){
        //save a reference to the original compile function
        if(!Handlebars.original_compile) Handlebars.original_compile = Handlebars.compile;
    
        Handlebars.compile = function(source){
            var s = "\\"+start,
                e = "\\"+end,
                RE = new RegExp('('+s+')(.*?)('+e+')','ig');
    
                replacedSource = source.replace(RE,function(match, startTags, text, endTags, offset, string){
                    var startRE = new RegExp(s,'ig'), endRE = new RegExp(e,'ig');
    
                    startTags = startTags.replace(startRE,'\{');
                    endTags = endTags.replace(endRE,'\}');
    
                    return startTags+text+endTags;
                });
    
            return Handlebars.original_compile(replacedSource);
        };
    };
    
    //EXAMPLE to change the delimiters to [:
    Handlebars.setDelimiter('[',']');
    

提交回复
热议问题