如何在javascript中创建动态插值字符串?

时间:2016-09-22 15:14:59

标签: javascript typescript ecmascript-6 string-interpolation

我正致力于创建可重用的UI组件,并试图弄清楚如何允许组件的使用者为组件的特定区域提供自己的模板。

我正在使用打字稿,并尝试利用字符串插值来实现这一点,因为它似乎是最合适的行动方式。

这是我到目前为止所做的:

export class Pager {
    pageNumber: number = 1;

    getButtonHtml(buttonContentTemplate?: string, isDisabled?: boolean): string {
        buttonContentTemlpate = buttonContentTemplate || '${this.pageNumber}';
        isDisabled = isDisabled || false;
        return `<button id="button-id" type="button"  ${!isDisabled ? '' : disabledAttribute}>
                    ${buttonContentTemplate}
                </button>`;
    }
}

我还有一些其他方法可以根据用户输入/交互更新页码,但我希望它可以在调用getButtonHtml时工作,返回值为<button id="button-id" type="button">1</button>,而是我得到<button id="button-id" type="button">${this.pageNumber}</button>

有没有办法让javascript再次评估字符串,并插入剩余的占位符?

我已查看有关此主题的MDN文章,并认为String.raw方法可能是我需要使用的方法,但我不确定无论如何我尝试了什么,我还没有让它发挥作用。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:5)

问题是Template literals会立即被解释。

您要做的是延迟加载模板。所以最好传入一个返回字符串的函数。

export class Pager {
    pageNumber: number = 1;

    getButtonHtml(template?: () => string, isDisabled=false): string {
        template = template || function() { return this.pageNumber.toString() };
        return `<button id="button-id" type="button"  ${!isDisabled ? '' : disabledAttribute}>
                    ${template()}
                </button>`;
    }
}

此外,您可以利用默认参数来避免||技巧。