【问题标题】:underscore template function override to inject HTML globally下划线模板函数覆盖以全局注入 HTML
【发布时间】:2016-01-06 12:07:04
【问题描述】:

我尝试使用 question 使用 require 函数全局覆盖模板函数,它适用于 templateSetting。

我尝试使用以下代码扩展/覆盖_.template 函数以包装 div。但是使用普通模板而不是像这样 <%= title %>

解析的模板
    define(['underscoreBase'], function(_) {
    _.template = function(str){
        return "<div class='test'>"+str+"</div>";
    };
    return _;
});

我们如何使用 _.template 字符串内容添加/包装一些 HTML 标记?请指教。

【问题讨论】:

  • 扩展和覆盖是完全不同的事情。你到底需要什么?
  • @HenriqueBarcelos 我想覆盖 _.template 字符串以用 HTML 包装

标签: javascript html underscore.js lodash underscore.js-templating


【解决方案1】:

你需要保留对原始template函数的引用:

define(['underscoreBase'], function(_) {
    var oldTemplate = _.template;
    _.template = function(str){
        return oldTemplate("<div class='test'>"+str+"</div>");
    };
    return _;
});

【讨论】:

  • 我试过了,但是得到了类似这个函数的东西 (obj){obj||(obj={});var _t,__p='',__e=.escape ,__j=Array.prototype.join;function print(){__p+=__j.call(arguments,'')}with(obj){__p+=' \r\n '; if (showRootHeader) { ; __p+='\r\n '+((__t=(title))==null?'':__t)+' \r\n '; } ; __p+='\r\n
  • 我已经试过了,现在 Uncaught ReferenceError: title is not defined :(
  • 即使我像 _.template = function(str){ return str; };返回相同的功能码
  • 代码中没有title。这可能是别的东西。
  • 模板 str 将具有
【解决方案2】:

我已经实现它像

var oldTemplate = _.template;
    function template(str, data) {
        return oldTemplate(
            "<div class='test'>"+str+"</div>",
            data
        );
    }
_.mixin({ template:template });
return _;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    相关资源
    最近更新 更多