在Jade中调用每个函数

Ven*_*tis 3 javascript google-maps-api-3 node.js keystonejs pug

我正在尝试在Jade模板中实现Google地图.使用KeystoneJS作为CMS,我有一些"配置文件"(基本上是人们的地址)我想要添加到地图作为标记.

block js
  script.
        var map;
        function initialize() {
            var mapOptions = {
              center: new google.maps.LatLng(51.0360272, 3.7359072),
              zoom: 8
            };
            map = new google.maps.Map(document.getElementById("map-canvas"),
                mapOptions);

        }

        google.maps.event.addDomListener(window, 'load', initialize);

block content
   .container
       script(src='https://maps.googleapis.com/maps/api/js?key=<GOOGLE_API_KEY>&sensor=false')

     if data.profiles
        each profile in data.profiles
            #{new google.maps.Marker({position: new google.maps.LatLng(profile.address.geo[1], profile.address.geo[0]), map: map, title: profile.name.full})}

    div(id="map-canvas", style="width:100%; height:700px;")
Run Code Online (Sandbox Code Playgroud)

地图显示正确,但是当我添加"每个"代码块时,我收到错误"无法读取未定义的属性'贴图'".

如何在Jade中添加一段在'each'上执行的js代码?

Jed*_*son 6

你真的很近,唯一的问题是可变的内部,即#{this_stuff}所有翡翠的上下文中执行(这不会有google对象,因为这是客户端).

这有点棘手,因为你在这里处理两个完全不同的javascript环境:服务器端客户端.

因此,您需要将jade中的服务器端变量输出到将在客户端执行的javascript代码中.

在相关的说明中,您可以在脚本块中使用Jade变量语法,但不能执行其他操作(如循环).

首先,让我们清理它,以便所有script标记都在js块中(假设您使用的示例KeystoneJS模板将位于<body>标记的底部)并正确生成这些配置文件:

block js
    script(src='https://maps.googleapis.com/maps/api/js?key=<GOOGLE_API_KEY>&sensor=false')
    script.
        var map;
        function initialize() {
            var mapOptions = {
                center: new google.maps.LatLng(51.0360272, 3.7359072),
                zoom: 8
            };
            map = new google.maps.Map(document.getElementById("map-canvas"),
                mapOptions);
        }

        google.maps.event.addDomListener(window, 'load', initialise);

    if data.profiles
        each profile in data.profiles
            script.
                new google.maps.Marker({
                    position: new google.maps.LatLng(#{profile.address.geo[1]}, #{profile.address.geo[0]}),
                    map: map,
                    title: "#{profile.name.full}"
                });

block content
   .container
        div(id="map-canvas", style="width:100%; height:700px;")
Run Code Online (Sandbox Code Playgroud)

这种情况越来越接近了(Jade会产生你现在所期望的),但是它还不会起作用,因为你可能会在函数运行之前将标记添加到地图中initialize.

它也没有转义值,因此"名称中的字符之类的东西会导致语法错误.

一种更强大的方法是填充客户端数组,然后在创建映射循环遍历该数组.我们还将使用JSON.stringify以确保正确转义值.

block js
    script(src='https://maps.googleapis.com/maps/api/js?key=<GOOGLE_API_KEY>&sensor=false')
    script.
        var map,
            profiles = [];

        function initialize() {
            var mapOptions = {
                center: new google.maps.LatLng(51.0360272, 3.7359072),
                zoom: 8
            };
            map = new google.maps.Map(document.getElementById("map-canvas"),
                mapOptions);

            for (var i = 0; i < profiles.length; i++) {
                new google.maps.Marker({
                    position: new google.maps.LatLng(profiles[i].geo[1], profiles[i].geo[0]),
                    map: map,
                    title: profiles[i].name
                });
            }
        }

        google.maps.event.addDomListener(window, 'load', initialise);

    if data.profiles
        each profile in data.profiles
            script.
                profiles.push({
                    geo: !{JSON.stringify(profile.address.geo)},
                    name: !{JSON.stringify(profile.name.full)}
                });

block content
   .container
        div(id="map-canvas", style="width:100%; height:700px;")
Run Code Online (Sandbox Code Playgroud)

请注意对!{variable}的更改,以便不转义JSON

最后,我建议profiles在路径.js文件中为视图构建数组,而不是在jade模板中进行.它更清洁,您不会<script>在页面中堆积大量标签.

所以你的路线看起来像这样(我假设有一点点给你的想法,并使用下划线使代码比vanilla javascript更整洁)

var keystone = require('keystone'),
    _ = require('underscore');

exports = module.exports = function(req, res) {

    var view = new keystone.View(req, res),
        locals = res.locals;

    // Load the profiles
    view.query('profiles', keystone.list('Profile').model.find());

    // Create the array of profile markers
    view.on('render', function(next) {
        locals.profileMarkers = locals.profiles ? _.map(locals.profiles, function(profile) {
            return { geo: profile.address.geo, name: profile.name.full };
        }) : [];
        next();
    });

    // Render the view
    view.render('profiles');

}
Run Code Online (Sandbox Code Playgroud)

然后在您的视图模板中:

block js
    script(src='https://maps.googleapis.com/maps/api/js?key=<GOOGLE_API_KEY>&sensor=false')
    script.
        var profileMarkers = !{JSON.stringify(profileMarkers)},
            map;

        function initialize() {
            var mapOptions = {
                center: new google.maps.LatLng(51.0360272, 3.7359072),
                zoom: 8
            };
            map = new google.maps.Map(document.getElementById("map-canvas"),
                mapOptions);

            _.each(profileMarkers, function(profile) {
                new google.maps.Marker({
                    position: new google.maps.LatLng(profile.geo[1], profile.geo[0]),
                    map: map,
                    title: profile.name
                });
            });
        }

        google.maps.event.addDomListener(window, 'load', initialise);

block content
   .container
        div(id="map-canvas", style="width:100%; height:700px;")
Run Code Online (Sandbox Code Playgroud)