[英]Insert a node inside html rendering with lit-element web components
As an exercise, given an html tag and a number of repetitions ( n ), I want to insert n times the tag node using a lit-element web component.作为练习,给定一个html标记和重复次数 ( n ),我想使用lit-element web 组件插入n次标记节点。 I'm stacked here:
我堆在这里:
import {LitElement, html, css} from 'lit-element';
export class WebComponent extends LitElement {
static get properties() {
return {
node: {type: String},
repetitions: {type: Number}
}
};
constructor() {
super();
this.node = "";
this.repetitions = 0;
}
render() {
var node = document.createElement(this.node);
return html`
<div>
${for (i = 0; i < this.repetitions; i++) {
// Insert node here
}}
</div>
`;
};
}
customElements.define('web-component', WebComponent);
Is this possible?这可能吗? How?
如何?
Yes, it is!是的!
What you're looking for is probably 'unsafeHTML', avaliable in the package 'lit-html/directives/unsafe-html';您正在寻找的可能是 'unsafeHTML',在 package 'lit-html/directives/unsafe-html' 中可用;
From the lit-html site:从 lit-html 网站:
import {unsafeHTML} from 'lit-html/directives/unsafe-html.js';
const markup = '<div>Some HTML to render.</div>';
const template = html`
Look out, potentially unsafe HTML ahead:
${unsafeHTML(markup)}
`;
In your example it would could be used like this:在您的示例中,可以这样使用:
render() {
return html`
<div>
${(() => {
let htmlString = '';
for (i = 0; i < this.repetitions; i++) {
htmlString += `<${this.node}>Custom Node!</${this.node}>`;
}
return html`${unsafeHTML(htmlString)}`;
})()}
</div>
`;
};
As the function name reads, be careful while using it!正如 function 名称所示,使用时要小心!
Also from the lit-html site:同样来自 lit-html 网站:
Note, this is unsafe to use with any user-provided input that hasn't been sanitized or escaped, as it may lead to cross-site-scripting vulnerabilities.
请注意,这对于任何未经清理或转义的用户提供的输入都是不安全的,因为它可能导致跨站点脚本漏洞。
Tested it and it works with latest release!经过测试,它适用于最新版本!
Can't tell your version but this seems to be around for a while now so you should be good!不能告诉你的版本,但这似乎已经存在了一段时间,所以你应该很好!
https://lit.dev/docs/templates/directives/#unsafehtml https://lit.dev/docs/templates/directives/#unsafehtml
import {unsafeHTML} from 'lit/directives/unsafe-html.js';
[...]
this.myhtml = "one<br />two"
[...]
render() {
return html`
<div>
${unsafeHTML(this.myhtml)}
</div>
`
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.