Lodash 3迁移至4:'lodash/string/template'替代方案及报错求助
解决方案
1. 包装Lodash 4的template函数,兼容Backbone调用上下文
Lodash 4的template函数默认生成严格模式的渲染函数,导致模板内的this指向undefined,而Lodash 3的非严格模式下this会继承调用时的上下文。通过包装函数可以恢复原有行为:
// 替换原导入语句 import { template as lodashTemplate, templateSettings } from 'lodash'; // 可选:若模板依赖Lodash 3默认的上下文变量名`obj`,恢复该设置 // templateSettings.variable = 'obj'; // 包装template函数,保留调用时的this上下文 function template(templateString, options) { const renderFn = lodashTemplate(templateString, options); // 返回新函数,将调用时的this传递给渲染函数 return function(context) { return renderFn.apply(this, arguments); }; } // 继续将template挂载到window.app中 window.app.template = template;
这个包装函数会确保模板执行时的this和Lodash 3一致,继承调用时的上下文(比如Backbone.View实例),直接解决Cannot set properties of undefined的错误。
2. 升级Backbone.js版本
Backbone 1.1.2是较旧版本,未适配Lodash 4的API变化。升级到最新稳定版(如1.4.1),官方已修复与新版Lodash的兼容问题,无需额外修改模板相关代码。
3. 修改模板内的this使用方式
如果模板中存在直接操作this的代码(如<% this._url_prefix = ... %>),可以改为通过上下文参数访问,避免依赖函数执行上下文:
<!-- 原模板代码 --> <% this._url_prefix = '/api' %> <!-- 修改后 --> <% obj._url_prefix = '/api' %>
同时设置templateSettings.variable = 'obj',让模板将上下文数据作为obj变量访问,这也是Lodash 3的默认行为。
内容的提问来源于stack exchange,提问作者Vlado
相关产品推荐
相关产品推荐

