我实质上是从后端 server.js 的数据库中选择 *,并将其传递到试图将数据解析到表中的句柄文件。 hbs 文件如下所示:
<table>
<tr>
<th>username</th>
<th>password (encrypted)</th>
<th>write privileges</th>
<th>admin privileges</th>
<th>modify</th>
<th>delete</th>
</tr>
{{#each user}}
<tr>
<td>{{ this.user }}</td>
<td>{{ this.password }}</td>
<td><script type="text/javascript"> if ({{ this.p_write }} == 1) { document.write('<i class="ti ti-check safe"></i>'); }</script></td>
<td><script type="text/javascript"> if ({{ this.p_admin }} == 1) { document.write('<i class="ti ti-check safe"></i>'); }</script></td>
<td><a href="#" class="warning"><i class="ti ti-edit"></i></td>
<td><a href="#" class="danger"><i class="ti ti-circle-minus"></i></a></td>
</tr>
{{/each }}
</table>
上面代码的输出也可以看到如下:
我想知道我用来检查
<script>
和 this.p_admin
的值(决定是否写入绿色复选标记)的 this.p_write
标签是否特别有效,以及是否有更好的方法在我的情况下这样做。我对此还很陌生,所以我可能没有找到一个明显的解决方案。谢谢。
正如评论中提到的,使用 Handlebars
if
条件而不是 document.write
。不仅是document.write()
强烈劝阻,它还将服务器端工作推送到客户端,这意味着数据将使用 JS 动态注入,而不是烘焙到 HTML 中。这会在内容可见之前添加短暂的延迟,从而影响可用性并损害 SEO。
这是一个可运行的示例,您可以适应您的用例(
<table>
是相关部分 - 其他所有内容都在那里,以便您可以在浏览器中将其作为堆栈片段进行交互):
// example boilerplate for the purposes of the snippet
const users = [
{user: "foo", password: "bar", p_write: false, p_admin: true},
{user: "baz", password: "baz", p_write: true, p_admin: false},
{user: "quux", password: "quux", p_write: false, p_admin: true},
];
const html = document.querySelector("#template").innerHTML;
const template = Handlebars.compile(html);
document.body.innerHTML = template({users});
table {
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 0.3em;
}
<script id="template" type="text/x-handlebars-template">
<table>
<tr>
<th>username</th>
<th>password (encrypted)</th>
<th>write privileges</th>
<th>admin privileges</th>
<th>modify</th>
<th>delete</th>
</tr>
{{#each users}}
<tr>
<td>{{user}}</td>
<td>{{password}}</td>
<td>
{{#if p_write}}
<i class="ti ti-check safe">test</i>
{{/if}}
</td>
<td>
{{#if p_admin}}
<i class="ti ti-check safe">test</i>
{{/if}}
</td>
<td>
<a href="#" class="warning">
<i class="ti ti-edit">test</i>
</a>
</td>
<td>
<a href="#" class="danger">
<i class="ti ti-circle-minus">test</i>
</a>
</td>
</tr>
{{/each}}
</table>
</script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/handlebars.js"></script>