javascript - Jade + express : Iterating over object in inline JS code (client-side)?

标签 javascript templates node.js express pug

我想根据它的 api 实现一个谷歌地图。我想添加一个基于坐标的路径。因此我从我的模型中获取我的坐标,并希望遍历对象以用这些点填充 map 。在我的 Jade 模板中,我包含这样的 api js 代码:

script(type='text/javascript')
    function initialize() {
      var myLatLng = new google.maps.LatLng(0, -180);
      var myOptions = {
        zoom: 3,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.TERRAIN
      };

      var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
      var flightPlanCoordinates = [

       - if (typeof(pins) != null)
           - var.pins.forEach(function(pin) {
                new google.maps.LatLng(pin.latitude, pin.longitude),
           - })
           new google.maps.LatLng(0,0)
      ];
      var flightPath = new google.maps.Polyline({
        path: flightPlanCoordinates,
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 2
      });

      flightPath.setMap(map);
    }

div#map_canvas(style='height: 500px; background-color: #990000;')

问题是:jade 渲染了这个片段

var flightPlanCoordinates = [

       - if (typeof(pins) != null)
           - var.pins.forEach(function(pin) {
                new google.maps.LatLng(pin.latitude, pin.longitude),
           - })
           new google.maps.LatLng(0,0)
      ];

因为它在 Jade 模板源中...... - if 等没有被解析!有什么想法吗?

谢谢!

最佳答案

整个 script 标签(所有缩进的)将通过 raw 传递,无需进一步解析。 Jade 做 HTML 模板而不是 HTML 模板加上嵌套的 javascript 模板。要将您的 pins 变量从 Jade 本地模板变量数据传递到脚本源代码,您必须执行一些其他方法,例如使用原始 Jade 来呈现仅调用您的 initialize 的微小脚本标记 函数将 pins 数据作为文字,或者将 pins 数据粘贴到 dom 某处,然后从那里读取。在你的脚本标签下面有类似的东西(伪代码,尚未测试)

- if (typeof(pins) != null)
  != "<script type='text/javascript'>"
  != "var pins = [];"
  - forEach pin in pins
    != "pins.push(new Pin(" + pin.latitude + ", " + pin.longitude + "));"
  != "initialize(pins);"
  != "</script>"

关于javascript - Jade + express : Iterating over object in inline JS code (client-side)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6270832/

相关文章:

javascript - 如何使用 JQuery 在 Android 浏览器中禁用 'Paste'?

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

C++ - 在单独的文件中实现内部模板类的模板方法

在浏览器中启用/禁用 JavaScript

javascript - 使用 jquery onclick 将网页滚动到 div

c++ - 模板化结构的括号括起来的初始值设定项列表

javascript - Node.js、Express.js 不向客户端发送文件

php - 在 Node.js 中模仿 PHP 的 __get(), __set() & __call() 魔术方法

node.js - 运行 Angular 项目会出现 Node-sass 错误

javascript - 如何将 .nextElementSibling 应用于下拉菜单的下一项