首页 > 解决方案 > Pug/Jade 和内联 javascript 计算

问题描述

我再次迷路了,试图在玉模板中进行一些简单的计算。

给定这个数据对象:

{
  "trade": {
    "name": "Mogens",
    "dst_currency": "EUR",
    "dst_value": 115.7,
    "src_price": null,
    "src_value": 2,
    "src_currency": "XMR",
    "date": null
    }
}

而这个哈巴狗来源:

table
  thead
    tr
      th Currency
      th Quantity
      th Price
      th Total
      th Date
  tbody
      tr
        script.
          if (trade.dst_currency === "EUR")
            trade.src_price = trade.dst_value / trade.src_value
          else
            trade.src_price = Number(trade.src_value) / Number(trade.dst_value)
        th.align-middle #{trade.dst_currency}
        th.align-middle #{trade.dst_value}
        th.align-middle= #{trade.src_price}
      th.align-middle #{trade.src_value} #{trade.src_currency}
      th.align-middle #{trade.date}

if trade.name === "Bob"
  h1 Hello Bob
else
  h1 My name is #{trade.name}

如果可能的话,这是如何做到的?我错过了什么?

标签: javascriptpug

解决方案


script在您的 Pug 代码中放置一个标签会script在您编译的 HTML 中呈现一个标签。它不会告诉 Pug 在编译时执行脚本标记中的任何 javascript。如果您想在编译代码时在 Pug 中运行 javascript,请使用无缓冲代码块

-
  // this is an unbuffered code block
  // that will update the value of `trade.src_price`
  // before it is rendered by Pug
  if (trade.dst_currency === "EUR") {
    trade.src_price = trade.dst_value / trade.src_value
  } else {
    trade.src_price = Number(trade.src_value) / Number(trade.dst_value)
  }

table
  thead
    tr
      th Currency
      th Quantity
      th Price
      th Total
      th Date
  tbody
    tr
      th.align-middle #{trade.dst_currency}
      th.align-middle #{trade.dst_value}
      th.align-middle= #{trade.src_price}
      th.align-middle #{trade.src_value} #{trade.src_currency}
      th.align-middle #{trade.date}

if trade.name === "Bob"
  h1 Hello Bob
else
  h1 My name is #{trade.name}

推荐阅读