我需要将用ejs语法创建的变量用于文件的脚本部分。
例如:
<% var test = 101; %>
<script>
var getTest = <%= test %>;
console.log(getTest);
</script>
但是在var getTest = <%= test %>;
行中,它显示错误Expression expected
,如下图所示。
有什么解决办法吗?
- 这里是静态HTML代码片段,以便更好地理解用例。*
<HTML>
<body>
<!--The below values are dynamic and passed from another file but here we kept it static. -->
<% var lineChartLabels = ["Feb 01"], lineChartData = [120]; %>
<canvas id="totalViewChart" style="width: 100%; height: 50%"></canvas>
<script>
var ctx = document.getElementById("totalViewChart").getContext("2d");
var labels = ["Feb 01"];
var data = [120];
var totalViewChart = new Chart(ctx, {
type: "line",
data: {
labels: labels, // lineChartLabels has to be passed here
datasets: [{
label: "No. of Viewers",
data: data, // lineChartData has to be passed here.
backgroundColor: ["rgba(255, 99, 132, 0.2)"],
borderColor: ["rgba(255, 99, 132, 1)"],
borderWidth: 1,
}, ],
},
options: {
animation: false,
width: 600,
height: 100,
responsive: false,
maintainAspectRatio: false,
scales: {y: {beginAtZero: true,},},
},
});
</script>
</body>
</html>
静态代码的期望输出
验证码:
<script data-test="<%= lineChartData %>">
var ctx = document.getElementById("totalViewChart<%= i %>").getContext("2d");
var labels = JSON.stringify("<%= lineChartLabels %>");
const getTest = document.currentScript.dataset.lineChartData;
var data = [120];
var totalViewChart = new Chart(ctx, {
type: "line",
data: {
labels: labels,
datasets: [{
label: getTest,
data: data, // lineChartData has to be passed here.
backgroundColor: ["rgba(255, 99, 132, 0.2)"],
borderColor: ["rgba(255, 99, 132, 1)"],
borderWidth: 1,
}, ],
},
options: {
animation: false,
width: 600,
height: 100,
responsive: false,
maintainAspectRatio: false,
scales: {y: {beginAtZero: true,},},
},
});
</script>
已尝试代码的输出
Try2
<script data-test="<%= lineChartData %>">
var ctx = document.getElementById("totalViewChart<%= i %>").getContext("2d");
var labels = "<%= JSON.stringify(lineChartLabels) %>";
const getTest = document.currentScript.getAttribute("data-test");
const data = "<%= JSON.stringify(lineChartData) %>"
var data2 = [120];
var totalViewChart = new Chart(ctx, {
type: "line",
data: {
labels: labels,
datasets: [{
label: data,
data: data,
backgroundColor: ["rgba(255, 99, 132, 0.2)"],
borderColor: ["rgba(255, 99, 132, 1)"],
borderWidth: 1,
}, ],
},
...
</script>
输出:尝试2
1条答案
按热度按时间s8vozzvw1#
我们可以在html的
<script>
标签中使用ejs变量吗?当然可以,不过你需要记住
<script>
元素中源代码的解析规则与HTML中其他元素的解析规则不同,这意味着<%=
并不适用,你需要结合使用<%-
和一些自定义转义来避免XSS攻击。我需要将用ejs语法创建的变量用于文件的脚本部分。
我建议使用
data
属性。或者如果值是一个对象(包括数组),使用JSON:
但在
var getTest = <%= test %>;
行中,它显示错误 * Expressionexpected *这看起来像是IDE或任何用于解析EJS / HTML / JS语法的插件中的一个错误。