JavaScript字符串文字重用组件

问题描述 投票:1回答:1

我正在尝试使用模板/字符串文字作为模板,我一直在观看有关该主题的多个视频,并一直关注this很棒的教程。

我认为使用可重用的块会很酷,因为某些元素会出现多次。

模板功能

function templater(strings, ...keys) {

    return function(data) {
        let temp = strings.slice();
        keys.forEach((key, i) => {
            temp[i] = temp[i] + data[key];
        });
        return temp.join('');
    }
};

示例块

let contentHead = `
    <header>
        ${'myHeader'}
    </header>
`

let contentFooter = `
    <footer>
        ${'myFooter'}
    </footer>
`

正在包装所有必要卡盘的模板

let contentTemplate = templater`
    <div>
        ${'contentHead'}
        ${'contentFooter'}
    </div>
    `

[这是我为模板设置数据的位置

const content = {
    myHeader: 'This is my header',
    myFooter: 'This is my footer',
    contentHead: contentHead,
    contentFooter: contentFooter,
}

这是我测试代码的方式

const myTemplate = contentTemplate(content);
console.log(myTemplate);

输出将是

<div>
   <header>
       myHeader
   </header>
   <footer>
       myFooter
   </footer>
</div>

如果我这样做而不调用像这样的变量

let contentTemplate = templater`
    <div>
         <header>
             ${'myHeader'}
         </header>
         <footer>
             ${'myFooter'}
        </footer>
    </div>


const content = {
    myHeader: 'This is my header',
    myFooter: 'This is my footer'
}

输出将是正确的

<div>
   <header>
       This is my header
   </header>
   <footer>
       This is my footer
   </footer>
</div>

所以为什么不起作用,我在JSON对象中调用了两个字符串文字变量,然后在模板程序函数中使用了它,因为这两个块在标记的模板函数之外传递,然后切换到模板没有自己的内容做任何事情?

我如何才能最好地解决此问题? :)

javascript templates ecmascript-6 string-literals
1个回答
0
投票

您的示例块不使用templater,它们是正常的模板字符串,并会立即插入。 contentHeadcontentFooter只是两个字符串,它们的插入方式与您在工作示例中的函数插入的myHeadermyFooter完全相同。

相反,也请在块上使用templater,并将它递归地将data传递给块函数:

function templater(parts) {
    return function(data) {
        let res = parts[0];
        for (let i=1; i<parts.length; i++) {
            const val = arguments[i];
            if (typeof val == "function") {
                res += val(data);
            } else {
               res += data[val];
            }
            res += parts[i];
        }
        return res;
    }
};

您会这样使用它:

const contentHead = templater`
    <header>
        ${'myHeader'}
    </header>
`;
const contentFooter = templater`
    <footer>
        ${'myFooter'}
    </footer>
`;
const contentTemplate = templater`
    <div>
        ${contentHead}
        ${contentFooter}
    </div>
`;

console.log(contentTemplate({
    myHeader: 'This is my header',
    myFooter: 'This is my footer',
}));

[如果要在data中通过块的名称来引用块,而不是在contentTemplate构造过程中直接通过变量引用来引用,您还可以检查data[key]是否为函数。

© www.soinside.com 2019 - 2024. All rights reserved.