2017-07-18 59 views
1

一个JavaScript模块要在帕格模板随机字符串我想用random-string的JavaScript模块。如何使用哈巴狗JS模板

首先,我通过NPM安装这样的:

npm install random-string 

然后在帕格模板我用这个:

.site 
    .title 
     - var string = randomString({length: 20}); 
     | #{string} 

但是在编译的文件,我得到这个错误:

randomString is not a function 

如何在pug js temaplte中使用第三方javascript函数?

+0

当然可以,但你需要把它作为'pug'呈现参数,因为你不能在''pug' require'。只需在外部环境中“需要”并通过它。 – MarcoL

回答

0

更新phpStorm文件看守

首先,安装哈巴狗CLI和随机字符串本地,

npm install pug-cli random-string --save 

然后安装文件看守,

enter image description here

原来的答复

设置并要求随机字符串作为局部变量,那么你可以在模板中访问它。例如,

template.pug

.site 
    .title 
     - var string = randomString({length: 20}); 
     | #{string} 

用哈巴狗

const pug = require('pug'); 

// Compile template.pug, and render a set of data 
console.log(pug.renderFile('template.pug', { 
    randomString: require('random-string') 
})); 
//-> <div class="site"><div class="title">o0rGsvgEEOHrxj7niivt</div></div> 

如果您使用的哈巴狗CLI编译它,在哈巴狗CLI的同一范围内安装随机字符串,通过字符串或文件指定选项。除非它是当你调用文件render()正在调用它在传递(如控制器)

pug -O "{randomString: require('random-string')}" template.pug 
+0

我正在使用phpStorm监视器来编译整个项目中的所有.pug文件。我可以在哪里配置你的指令? –

+0

@ A.B。开发人员您是否在使用pug-cli以及phpStorm文件监视器?您可以将'-O'{randomString:require(“random-string”)}''传递给观察者设置中的参数 –

+0

我向参数添加了“-O”{randomString:require(“random-string”)}现在我在编译时出现这个错误:'undefined:1 ('{randomString :) ^^^^^^^^^^^^^^^^ SyntaxError:无效或意外的标记' –

0

你的哈巴狗文件不会有randomString的范围。

例如

this.render("[pugFilename]", { 
    randomString = require("randomstring") // whatever package name you're using 
} 

就个人而言,我喜欢做的视野之外,并请求该视图中查看脚本任何非视的东西呈现,在那里我可以。

在帕格的语法可以开始看起来非常凌乱,否则,变得难以遵循。

您可以切换出上面的代码在你的问题的代码,它应该正常工作,但我建议你改变你的变量名(或键)更有意义。

e.g

this.render("[pugFilename]", { 
    randomStr: randomString({ length: 20 }) 
});