【问题标题】:Pug Unbuffered Code Variable Interpolation Not Working but Buffered Code doesPug 无缓冲代码变量插值不起作用,但缓冲代码可以
【发布时间】:2019-02-03 14:27:14
【问题描述】:

我正在尝试使用 Pug 进行模板创建一个快速应用程序。我无法弄清楚为什么当我使用无缓冲变量插值时,对象是未定义的,但是当我删除破折号时它似乎工作得很好(减去它实际上显示的对象)

//index.pug

extends layout

block campground 
  - var campgrounds = '#{camps}'
    .row
      each campground in campgrounds
        div.col-md-3.col-sm-6
          div
            img(src=`${campground.image}` class='img-thumbnail')
            a(href=`/campgrounds/${campground._id}`)
              h4.caption.text-center #{campground.name}





//app.js

app.get('/campgrounds', async (req, res) => {
    try {
        const camps = await Camp.find();
        res.render('index', { camps: camps });
    } catch (ex) {
        res.status(500).send('internal error');
    }
});

语法 1:

- var campgrounds = '#{camps}'

生产:

语法 2:

var campgrounds = '#{camps}'

生产:

【问题讨论】:

    标签: express pug


    【解决方案1】:

    我相信你可以:

    1. 删除- var campgrounds = '#{camps}' 行并替换each campground in camps 上的each campground in campgrounds 行(参见下面的代码sn-p)。
    2. 或者您也可以在- var campgrounds = camps 上替换- var campgrounds = '#{camps}'(您不需要在代码行中插值)。

    $(function() {
    
        // in your code you get `camps` from DB
        // const camps = await Camp.find();
        const camps = [{name: 'Camp1'}, {name: 'Camp2'}, {name: 'Camp3'}];
    
        var json = {
            camps: camps
        };
    
        // jade compile
        // instead of your function res.render(...);
        $("#so").html(jade.compile($("#jadehi").html())(json));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jade/0.27.7/jade.min.js"></script>
    
    <div id="so">SEO(please enable javascript~)</div>
    <pre id="jadehi" style="display:none">
    .content
      .row
        each campground in camps
          div.col-md-3.col-sm-6
            div.
              Campground: #{campground.name}
              <!-- img(src=`${campground.image}` class='img-thumbnail') -->
              <!-- a(href=`/campgrounds/${campground._id}`) -->
                <!-- h4.caption.text-center #{campground.name} -->
    
    </pre>

    【讨论】:

    • 你的第一个建议就像魅力一样。我想我误解了代码插值的目的。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多