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

pei*_*ent 1 javascript string-interpolation typescript ecmascript-6

我正在努力创建一个可重用的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>`;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

我看过关于这个主题的MDN文章,并认为该String.raw方法可能是我需要使用的方法,但我不确定,无论我尝试什么,我都没有得到它的工作.

任何帮助将不胜感激.

sty*_*fle 5

问题是模板文字会立即被解释.

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

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>`;
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,您可以利用默认参数来避免这种||伎俩.