JADE + EXPRESS:在内联JS代码(客户端)中迭代对象?

Tro*_*nic 10 javascript templates node.js express pug

我想基于它的api实现谷歌地图.我想基于坐标添加路径.因此,我从我的模型中获取坐标,并希望迭代对象以使用此点填充地图.在我的玉模板中,我包含这样的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;')
Run Code Online (Sandbox Code Playgroud)

问题是: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)
      ];
Run Code Online (Sandbox Code Playgroud)

因为它是在玉模板源... ... - 如果等不解析!有任何想法吗?

谢谢!

Pet*_*ons 16

整个脚本标记(在其下缩进的所有内容)将通过raw传递而无需进一步解析.Jade做HTML模板而不是HTML模板加上嵌套的javascript模板.要将您的pins变量从jade本地模板变量数据传递到脚本源代码,您必须执行一些其他方法,例如使用原始jade来呈现一个小的脚本标记,只需initializepins数据作为文字调用您的函数,或者粘贴您的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>"
Run Code Online (Sandbox Code Playgroud)


小智 5

我将值作为隐藏的输入元素传递,例如:

    input(type='hidden', id='variableName', value='#{variableName}')
Run Code Online (Sandbox Code Playgroud)

通过jQuery访问:

    $("#variableName").val()
Run Code Online (Sandbox Code Playgroud)