从Harp.js中的EJS模板调用另一个文件上的javascript函数 [英] Call javascript functions on another file from an EJS templates in Harp.js

查看:169
本文介绍了从Harp.js中的EJS模板调用另一个文件上的javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此处尝试使用Harp.js创建网站.我使用ejs模板,并希望将一些有用的javascript函数存储在中央文件中.我怎么做?我尝试使用

<% include _render_util.js %>

但是它不起作用(似乎未解析js文件).

有什么想法吗? 谢谢!

解决方案

尽管有一些方法可以使这项工作(有时),但是Harp.js并没有内置这种方法.强制执行此行为通常需要花费一些时间进行调试,并导致意外的问题.

这是我进行的一项快速实验,可以正常工作(我并没有对其进行全面测试):

helpers.ejs

我创建了一个say_hello函数,该函数带有一个名称并输出字符串Hello, {name}.

<%
say_hello = function (name) {
  return 'Hello, ' + name;
}
%>

index.ejs

I include helpers.ejs(上述文件)在第一行中,然后在第二行中使用该函数.输出<h1>Hello, beautiful</h1>.

<% include helpers.ejs %>
<h1><%= say_hello("beautiful") %></h1>

要点示例: https://gist.github.com/jorgepedret/816c2b3985ad12cef022

GitHub上有一个未解决的问题,正在讨论此问题 https://github.com/sintaxi/harp/issues/272

此示例比推荐的解决方案更像是骇客.我曾见过一些情况以意外的方式中断.

Trying to make a website with Harp.js here. I use ejs templates, and want to store some useful javascript functions in a central file. How do I do that? I tried to use

<% include _render_util.js %>

But it does not work (seems like js file is not parsed).

Any ideas? Thanks!

解决方案

Although there are ways of making this work (sometimes), it's not something that was deliveratly built into Harp.js. Forcing this behaviour often takes time to debug and causes unexpected issues.

Here is a quick experiment I made that works (I didn't throughly test it):

helpers.ejs

I created a say_hello function that takes a name and outputs the string Hello, {name}.

<%
say_hello = function (name) {
  return 'Hello, ' + name;
}
%>

index.ejs

I include helpers.ejs (the file mentioned above) in the first line and then use the function in the second line. That outputs <h1>Hello, beautiful</h1>.

<% include helpers.ejs %>
<h1><%= say_hello("beautiful") %></h1>

Example gist: https://gist.github.com/jorgepedret/816c2b3985ad12cef022

There's an open issue on GitHub discussing this issue https://github.com/sintaxi/harp/issues/272

This example is more of a hack than a recommended solution. I've seen cases where it breaks in unexpected ways.

这篇关于从Harp.js中的EJS模板调用另一个文件上的javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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