如何用 link (Pug) 替换文本中的单词?

How to replace word in text with link (Pug)?

我是 Pug 的初学者,我正在尝试解决以下任务:以下单词的每次出现(在文本中)都应成为 link 到下面定义的目的地:

sed -> https://google.com liq -> https://facebook.com

This 如我所料,但将锚标记保留为字符串。

- var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar elementum integer sed neque volutpat ac. Facilisis liq odio morbi quis commodo odio aenean . Vel facilisis volutpat liq velit. Viverra aliquet liq sit amet tellus cras adipiscing sed.";
- var url = '#[a(href="https://google.com") sed]'; //I tried with these ones too - var url = '<a href="https://google.com">sed</a>'; var url = 'a(href="https://google.com)sed'
- var res = str.replace(/sed/g, url);

p #{res}


Here my latest atempt:

mixin link(href, name)
  a(href=href target!=attributes.target )= name

//+link('https://google.com', 'Google')(target="blank")

- var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar elementum integer sed neque volutpat ac. Facilisis liq odio morbi quis commodo odio aenean . Vel facilisis volutpat liq velit. Viverra aliquet liq sit amet tellus cras adipiscing sed.";
- var link = +link('https://google.com', 'Google')(target="blank");
- var res = str.replace(/sed/g, link);

p #{res}

我从未见过像以前那样在 javascript 代码块中使用 Pug mixin。我很惊讶它甚至完全输出锚标记。

也就是说,您可以使用 unescaped string interpolation 语法 (!{variable}) 而不是常规的字符串插值语法 (#{variable}) 来获取 link 以呈现作为 link.

你的情况:

p !{res}

但请记住来自 Pug documentation 的警告:

Caution

Keep in mind that buffering unescaped content into your templates can be mighty risky if that content comes fresh from your users. Never trust user input!