【问题标题】:Checking for undefined variable in ejs template检查 ejs 模板中的未定义变量
【发布时间】:2019-01-03 13:55:34
【问题描述】:

我将 api 天气数据传递给我的 ejs 模板。我有一个条件语句来检查是否存在任何 api 数据。无论如何,我总是收到以下错误:

无法读取未定义的属性“临时”

条件语句 if 在脚本标签内。

<script>


    if ( JSON.parse('<%-locals.forecast.temps[0]%>') != undefined){

    console.log('there is data');


    var height = 500;
    var width = 800;
    var margins = {
        left: 40,
        top: 40,
        right: 40,
        bottom: 40
    }



            var barData = [
                {strength:JSON.parse('<%-locals.forecast.temps[0]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[1]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[2]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[3]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[4]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[5]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[6]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[7]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[8]%>')},
                {strength:JSON.parse('<%-locals.forecast.temps[9]%>')},
            ]

【问题讨论】:

  • 你能告诉我们你将数据传递给模板的代码吗
  • locals.forecast 未定义。
  • 使用以下代码`res.render('index', {data:api_data, forecast:api_forecast});`将代码传递给我的routes.js文件中的ejs模板。我确实通过控制台日志确认 api 数据被正确提取。
  • 那么locals 是什么?

标签: node.js express ejs


【解决方案1】:

原来是脚本标签在服务端渲染ejs模板后运行客户端。因此,即使 locals.forecast.temps[0] 可以在脚本标签之外工作,它也不会在其中工作。我最终创建了一个单独的变量,用于在模板引擎运行时存储服务器端的值,然后将该变量传递给脚本客户端,以便无需返回服务器即可访问它。

ejs 模板中的脚本标签之外......

<% var forecast_data = locals.forecast.temps  %>

脚本标签内...

var get_forecast_data = '<%= forecast_data %>'

这篇文章很有帮助:Can a js script get a variable written in a EJS context/page within the same file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    相关资源
    最近更新 更多