typescript 使用打字稿使用模板创建 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32049527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using typescript to create HTML using template
提问by Ziv Weissman
Trying out typescript, I want to achieve the following thing:
尝试打字稿,我想实现以下目标:
Getting a question text and a number from server and displaying it in DOM somewhere, using typescript.
使用打字稿从服务器获取问题文本和数字并将其显示在 DOM 中的某处。
Currently I have the following .ts file:
目前我有以下 .ts 文件:
class QuestionResponse {
constructor(public questionText, public questionNumber) {
}
}
function questioner(question: QuestionResponse) {
return '<div data-val-id="${QuestionNumber}"> ${QuestionText} </div>';
}
var testQuestion = new QuestionResponse("Question text number 5", 5);
//this will be replaced by .innerHTML of some element:
alert(questioner(testQuestion));
This does not replace the ${QuestionNumber} with the question.QuestionNumber... nor the Text. I don't want to use string appends, I want to use clean html, preferably on a seperate .html file.
这不会将 ${QuestionNumber} 替换为 question.QuestionNumber... 或 Text。我不想使用字符串追加,我想使用干净的 html,最好是在单独的 .html 文件中。
Basically I'm asking: Is it possible using typescript, if yes, how? If not, what would be the best practice way to achieve this using angularjs? (but still using typescript)
基本上我在问:是否可以使用打字稿,如果是,如何使用?如果没有,使用 angularjs 实现这一目标的最佳实践方法是什么?(但仍在使用打字稿)
回答by Alon Amir
The correct syntax is:
正确的语法是:
function questioner(question: QuestionResponse) {
return `<div data-val-id="${question.questionNumber}"> ${question.questionText} </div>`;
}
The important part here is the usage of ` (backquote/backtick)
Wrap your string with ` instead of " and 'to make use of the ${}
syntax.
这里的重要部分是使用 `(反引号/反引号)
用 ` 而不是 " 和 ' 包裹你的字符串以利用${}
语法。
This is a TypeScript (and ES6) feature.
这是一个 TypeScript(和 ES6)特性。