获取ejs模板中的url参数 [英] Getting the url parameters in an ejs template
问题描述
我正在尝试基于URL参数创建一个ejs条件,例如,如果测试参数存在于localhost:3000 / page?test,那么显示一个div,否则不显示它。
I am trying to create an ejs conditional based on a URL parameter, for example, if the test parameter exists at localhost:3000/page?test, then show a div, else dont show it.
我的ejs模板类似于:
My ejs template looks something like:
<% include header %>
<div class="row">
<%if (title !== "homepage") {%>
<%= title %>
<div>
<% include nav %>
</div>
<%}%>
<div>
</div>
</div>
<% include footer %>
有没有办法直接从ejs文件访问URL参数?例如,<%= title%>工作正常,是否有<%= req.query%>?
Is there a way to access the URL parameters directly from the ejs file? For example, the <%= title %> works fine, is there something like <%= req.query %>?
我也在使用快递。
推荐答案
你可以通过它很容易作为第二个参数中的对象 render()
You can pass it easily as an object in the second argument to render()
app.get('/someurl', function(req, res, next) {
res.render('filename', {query : req.query});
});
您还可以使用本地人
变量
app.get('/someurl', function(req, res, next) {
res.locals.query = req.query;
res.render('filename');
});
当与在所有其他路线之前运行的一般路线一起使用时非常有用,使得变量以下所有路线均可使用
which is very useful when used with a general route that runs before all the other routes, making the variable available in all the following routes
app.use(function(req, res, next) {
res.locals.query = req.query;
res.locals.url = req.originalUrl;
next();
});
并且它在您呈现为查询的文件中可用
etc
and it's available in the file you're rendering as query
etc
<% if (query == "something") { %>
<div id="crazy_shit">
<a href="<%- url -%>">Here</a>
</div>
<% } %>
作为旁注,如果查询
原因没有定义,你会在EJS中因使用未定义的变量而出错,这可能很烦人。
As a sidenote, if query
for some reason isn't defined, you'll get an error in EJS for using an undefined variable, which can be annoying.
我通常通过使用对象来解决这个问题,因为检查对象属性不会触发错误,并且很容易确保对象始终在顶部具有初始值每个EJS模板。
在路线中这样做
I usually solve this by using an object instead, as checking object properties does not trigger errors, and it's easy to make sure the object always has an initial value at the top of each EJS template.
It's done like this in the routes
app.user(function(req, res, next) {
res.locals.stuff = {
query : req.query,
url : req.originalUrl
}
next();
});
然后在模板中
<% stuff = typeof stuff !== 'object' ? {} : stuff %>
// later on
<% if ( stuff.query == "something") { %>//does not throw error if property not defined
<div id="crazy_shit"></div>
<% } %>
即使 stuff.query
已定义,条件只是失败并且它不会抛出错误,如果 stuff
本身或任何其他变量未被定义。
which even if stuff.query
is defined, the condition just fail and it doesn't throw an error like it would if stuff
itself, or any other variable, wasn't defined.
这篇关于获取ejs模板中的url参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!