本文介绍了带有主干导轨的 Rails:EJS 文件中的资产助手(image_path)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 codebrew/backbone-rails 的 Rails 3.1 应用程序.在 .jst.ejs 模板中,我想包含一个图像,如下所示:

I have a Rails 3.1 app that uses the codebrew/backbone-rails. In a .jst.ejs template, I would like to include an image, like so:

<img src="<%= image_path("foo.png") %>"/>

当然,资产助手在 JavaScript 中不可用.

But of course the asset helpers are not available in JavaScript.

链接 ERB (.jst.ejs.erb) 不起作用,因为 EJS 语法与 ERB 冲突.

Chaining ERB (.jst.ejs.erb) does not work, because the EJS syntax conflicts with ERB.

这是我所知道的:

  • 资产助手在浏览器中不可用,因此我需要在服务器端运行它们.
  • 我可以通过让服务器将各种资产路径转储到 HTML(通过数据属性或 <script> 和 JSON)并在 JS 中读取它们来解决这个问题,但这似乎更像是笨手笨脚的.
  • The asset helpers are not available in the browser, so I need to run them on the server side.
  • I can work around the problem by making the server dump various asset paths into the HTML (through data attributes or <script> and JSON) and reading them back in JS, but this seems rather kludgy.

有没有办法以某种方式使用 EJS 文件中的资产助手?

Is there a way to somehow use the asset helpers in EJS files?

推荐答案

实际上,有一种方法可以链接一个 .jst.ejs.erb 文件,虽然它相当没有文档,我只是通过查看 EJS 找到它测试用例.您可以告诉 EJS 使用 {{ }}(或 [% %] 或其他任何您想要的)而不是 <% %>,然后 ERB 不会尝试评估您的 EJS 调用.

There is a way, actually, to chain a .jst.ejs.erb file, although it's fairly undocumented, and I only found it through looking at the EJS test cases. You can tell EJS to use {{ }} (or [% %] or whatever else you want) instead of <% %>, and then ERB won't try to evaluate your EJS calls.

确保在您的代码中的某处需要 EJS(我刚刚在我的 Gemfile 中包含了 gem 'ejs'),然后创建一个包含以下内容的初始化程序(我称之为 ejs.rb):

Make sure to require EJS somewhere in your code (I just included gem 'ejs' in my Gemfile), and then create an initializer (I called it ejs.rb) that includes the following:

EJS.evaluation_pattern    = /{{([sS]+?)}}/
EJS.interpolation_pattern = /{{=([sS]+?)}}/

然后确保将您的模板重命名为 .jst.ejs.erb,并用 {{ }} 替换现有的 <% %> EJS 解释代码.如果您想使用除 {{ }} 以外的其他内容,请更改初始化程序中的正则表达式.

Then just make sure to rename your templates to .jst.ejs.erb, and replace your existing <% %> EJS-interpreted code with {{ }}. If you want to use something other than {{ }}, change the regular expressions in the initializer.

我希望 Sprockets 中有一个选项可以通过配置来处理这个问题,而不必显式包含 EJS,但就目前而言,我所知道的还没有办法做到这一点.

I wish there were an option in Sprockets to handle this through the config rather than having to explicitly include EJS, but as of the moment, there's no way to do that that I know of.

这篇关于带有主干导轨的 Rails:EJS 文件中的资产助手(image_path)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:04