2016-09-22 79 views
1

我正在創建一個可重用的UI組件,並試圖找出如何讓組件的使用者爲組件的特定區域提供自己的模板。如何在JavaScript中創建動態插值的字符串?

我正在使用打字稿,並試圖利用字符串插值來實現這一點,因爲它似乎是最合適的操作過程。

這是我到目前爲止有:

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方法可能可能是我需要使用的方法,但我不確定,無論我嘗試什麼,我都沒有得到它工作。

任何幫助將不勝感激。

+3

[ES2015 template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)或許多可用模板系統之一 – Pointy

+0

也許我的問題不清楚。我正在使用模板文字,它正在爲disabled屬性工作,但'$ {buttonContentTemplate}'也包含一個模板文字,並且沒有被評估。而不是把'1'放在那裏(如果模板被評估,會發生這種情況),它會放入'$ {this.pageNumber}'。有沒有辦法強制javascript再次評估,並進一步更換? – peinearydevelopment

+0

應包含在' – Monah

回答

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>`; 
    } 
} 

此外,您可以利用默認參數來避免||詭計。

相關問題