简体   繁体   English

在静态文件中表达,扩展变量

[英]Express, expand variable in static file

I am using express on a nodejs platform and serve my javascript library files using this directive 我在nodejs平台上使用express并使用此指令提供我的javascript库文件

app.use('/static', express.static(__dirname + '/static'))

Now I want to be able to write something like that, inside one of these static files 现在,我希望能够在这些静态文件之一中编写类似的内容

[..] var host = <%= host %> [..]

Is there any possibility to expand variables inside statically served files? 是否有可能在静态提供的文件中扩展变量?

Here's an idea you might want to refine: 这是您可能需要改进的一个想法:

var ejs = require('ejs');

//Express.js setup
...

app.use('/public/js/myfile.js', function(req, res){
    var f = ejs.compile('var host = <%= hostname %>;');
    var fileContent = f({hostname: 'somevalue'});
    res.setHeader('Content-Type', 'application/javascript');
    res.setHeader('Content-Length', fileContent.length);
    res.send(fileContent);
});
app.use(express.static(path.join(__dirname, 'public')));

//Routes definition
...

I used ejs since that's what you already use. 我使用了ejs,因为那是您已经使用的。 So the idea is to have a middleware that catches requests to those "dynamic" javascript files, and use the template engine to compile the content. 因此,这个想法是要有一个中间件来捕获对那些“动态” javascript文件的请求,并使用模板引擎来编译内容。

Note that I use a simple string variable here, but you could read the file from disk and then compile it. 请注意,我在这里使用了一个简单的字符串变量,但是您可以从磁盘读取文件,然后进行编译。

Cheers 干杯

您可以使用loDash的模板使用与快递lodashinexpress

Please see my answer here: https://stackoverflow.com/a/19812753/2728686 请在这里查看我的答案: https : //stackoverflow.com/a/19812753/2728686

Using the Jade templating engine you can serve static files and send serverside javascript variables to the static HTML files (or to any jade templates), as such: 使用Jade模板引擎,您可以提供静态文件, 并将服务器端javascript变量发送到静态HTML文件 (或任何jade模板),例如:

Server side (server.js): 服务器端(server.js):

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.get('/', ensureAuthenticated, function(request, response){
    response.render('index', { data: {currentUser: request.user.id} });
});

app.use(express.static(__dirname + '/www'));

views/index.jade: views / index.jade:

!!! 5
script(type='text/javascript')
    var local_data =!{JSON.stringify(data)}

include ../www/index.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM