EJS包含在单独的ejs文件中定义的功能 [英] EJS include functions defined in a separate ejs file

查看:158
本文介绍了EJS包含在单独的ejs文件中定义的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试包含一个ejs文件,该文件包含用于设置视图的功能。这些功能被定义为辅助工具。我试过使用:

I am trying to include an ejs file that contains functions for setting up my views. These functions were defined to be used a helpers. I have tried using:

<% include helpers.ejs %>

但是当我尝试使用此文件中的函数时:

But when I try to use the function from this file:

<% module_start('$body', [{name:'display',value:'block'}], 'body'); %>

我收到错误:

Reference Error: module_start is not defined

当我复制代码时从 helpers.ejs到我的原始视图文件 test.ejs,它可以按预期工作。我经历了几个答案,在这种情况下,
仍然让我感到困惑。

When I copy over the code from 'helpers.ejs' to my original view file, 'test.ejs', it works as expected. I have gone through several answers and, am still confused what am I doing wrongly in this case.

感谢您的提前帮助。

推荐答案

经过数小时尝试各种设想的解决方案后,我找到了一个可行的解决方案。该解决方案是从以下地方借来的:

After some grueling hours of trying every conceived solutions out there, I have landed upon a solution that is working. The solution was borrowed from:

EJS函数

看着这段代码中介绍的解决方案,我更新了我的'helpers.ejs 到 helpers.js。之后,我将导出的功能从'helpers.js'添加到ejs渲染上下文对象中:

Looking at the solution presented in this code, I updated my 'helpers.ejs' to 'helpers.js'. Following this, I added the exported functions from 'helpers.js' to the ejs render context object:

const ejs_helpers = require('path/to/helpers.js');

...

ejs.renderFile('filename', { helpers:ejs_helpers, ...}, (err,data)=>{});

在ejs视图文件中:

<%- helpers.function_name(params); %>

这大大改变了我最初解决问题的方式。使用普通的ejs帮助程序文件,这些函数在控制流语句之间包含HTML。在此处显示的情况下,函数返回纯字符串。请注意带有 Scriptlet标签的-。

This considerably changes how I initially approached the problem. With plain ejs helper file, the functions include HTML in between the control flow statements. In the case presented here, the functions returns plain string. Notice the '-' with the 'Scriptlet' tag.

希望这对某人有帮助。

这篇关于EJS包含在单独的ejs文件中定义的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆