我正在制作一个模板,我正在尝试使用express和ejs渲染模板.至于节点应用程序的标准结构,我有app.js文件,其中包含如下函数:
app.locals.getFlag = function(country) {
var flag_img_name = "";
if (country.toLowerCase() == "us") {
flag_img_name = "flag_us16x13.gif";
}
else if (country.toLowerCase() == "ca"){
flag_img_name = "flag_ca16x13.gif";
}
return flag_img_name;
}
Run Code Online (Sandbox Code Playgroud)
我有some_template.ejs文件调用此函数,如下所示:
<img src="http://some_url_path/<%=getFlag(data_point[0].country_name) %>" width="16" height="14" alt="country" >
Run Code Online (Sandbox Code Playgroud)
它工作得很好.但是,我有大约15-20个这样的函数,我不想在app.js中定义所有这些函数.还有其他地方可以定义这些函数并在模板中调用它们,就像我现在一样吗?如果是,那么定义它们的方式是什么,以便它们像现在一样可以访问.
我是节点,表达和ejs的新手,并不确定不同的技术.如果有人可以为它揭开光芒,那就太好了.先感谢您.
我已经从 .EJS 模板中名为 items 的数组创建了一个按钮/文本的 html 列表。如何将特定项目的 id (item.id) 传递给按钮的函数,以便将正确的数据发送到我的 api?谢谢。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Menu</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
function print(id) {
$.ajax({
url: "https://www.example.com/api/1/print",
type: "POST",
data: {
"item_id": id
},
dataType: "json",
success: function (result) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
};
</script>
</head>
<body>
<h2>Menu</h2>
<ul>
<% for(item of items) { %>
<li>
<button onclick="print(item.id)">PRINT</button>
<%= item.name %> - <%= item.id %>
</li>
<% } %>
</ul> …Run Code Online (Sandbox Code Playgroud)