为了账号安全,请及时绑定邮箱和手机立即绑定

是否有使用 jsViews/jsRender 和 Web 组件作为模板引擎的用例?

是否有使用 jsViews/jsRender 和 Web 组件作为模板引擎的用例?

慕姐4208626 2023-07-20 15:37:17
我正在编写一些 Web 组件,我想使用 jsViews $.link 功能作为我的模板引擎。我已经能够使用 $.render 来替换 ShadowRoot 克隆内容的 .innerHTML,但我只能通过以下方式使用 $.link 。只是看起来“肮脏”,必须添加一个额外的 div 来链接。有一个更好的方法吗?这里有任何性能问题吗?:const template = document.createElement('template');template.innerHTML = `<div id="todo-item-tmpl"></div>`;class TodoItem extends HTMLElement {    constructor() {        this._tmpl = $.templates('#todoItems');        this._shadowRoot = this.attachShadow({ 'mode': 'open' });        this._shadowRoot.appendChild(template.content.cloneNode(true));        this._todoTmpl = this._shadowRoot.querySelector('#todo-item-tmpl');        this._tmpl.link(this._todoTmpl, this._myDataObj);    }}
查看完整描述

1 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

这是可能的方法,如示例的修改版本所示:https://jsfiddle.net/BorisMoore/z9wnyh5q/

它们不是将模板定义为脚本元素的内容,而是使用标记字符串来定义 - 以保留 Web 组件本身的 HTML 标记。

<html>

  <head>...</head>

  <body>

    <to-do-app></to-do-app>

  </body>

</html>

项目模板可以是全局定义的命名模板,


$.templates("todoItemTmpl", todoItemTmpl}  // markup string for item template

或者可以将主模板作为资源(https://www.jsviews.com/#d.templates@tmpl-resources),以实现更好的封装:


this._tmpl = $.templates({

  markup: todoappTmpl, // markup string

  templates: {todoItemTmpl: todoItemTmpl}  // markup string for item template

});

this._tmpl.link(this._wrapper, this._todos, this);对( https://www.jsviews.com/#jsvtmpllink )的调用需要将 HTML 元素(或 jQuery 选择器)作为第一个参数,该元素是包装呈现的数据链接内容的容器元素。它不能直接是文档片段(影子根),因此您需要提供包装元素(并且还可以选择插入样式元素),例如通过以下代码:


// Create a wrapper element

this._wrapper = document.createElement('span');


// and a style element...

this._style = document.createElement('style');

this._style.textContent = todoappStyle; // Stylesheet markup


// Both inserted under the shadow root

this._shadowRoot = this.attachShadow({ mode: "open" });

this._shadowRoot.append(this._style, this._wrapper);


// Render and data-link

this._tmpl.link(this._wrapper, this._todos, this);


查看完整回答
反对 回复 2023-07-20
  • 1 回答
  • 0 关注
  • 88 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信