I have a Rails application, and would like to import an ejs file into my existing haml file

index.haml:

- str = controller.render_to_string file: "random.ejs", layout: false
= str.html_safe

ranodm.ejs (works):

<div>Random</div>

ranodm.ejs (DOES NOT WORK):

<img src="<% if (sc_image) { %><%= sc_image %><% } else { %>/assets/arrow-head-260x260.png<% } %>">    

I get the following error:

Syntax error, unexpected '{', expecting keyword_then or ';' or '\n'
...('<img src="'); if (sc_image) { ;@output_buffer.append= ( sc...
有帮助吗?

解决方案

So it looks like rails is interpreting the ejs file as ruby and chokes when it hits the javascript syntax. Here's 2 suggestions:

  1. Use the ruby-ejs gem to render the partial to a text string using javsccript.

    EJS.evaluate("Hello <%= name %>", :name => "world")

    # => "Hello world"

    You would just need to load the file in to pass its contents to evaluate without trying to parse it first. File.open("app/views/controller_name/_my_awesome_template.html.ejs").read

  2. You could rewrite the ejs partial in ruby unless you're using it elsewhere in a javascript context.

其他提示

You could rewrite the conditional to avoid using brackets like this:

<img src="<% sc_image ? sc_image : "/assets/arrow-head-260x260.png"%>"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top