最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ruby on Rails: Render HTML partial as a one line of string - Stack Overflow

programmeradmin3浏览0评论

Is there a way to render a html.erb partial as a one line of string?

I am trying to render a _foo.html.erb partial inside a javascript, such that I can use the whole html document as a string variable.

I have tried the following code:

var foo = "<%= render :partial => "foo" %>";

And inside _foo.html.erb, let's say I have the following:

<h1>Hello</h1>
<p>World</p>

This way will give me a syntax error in javascript because there is CRLF in the partial. But if I write code like...

<h1>Hello</h1>" +
"<p>World</p>

Now, it's not an error in javascript. I can do the latter way, but it is a disaster if the partial contains a lot of lines of code with ruby script.

Would there be any alternative way?

Thanks in advance.

Is there a way to render a html.erb partial as a one line of string?

I am trying to render a _foo.html.erb partial inside a javascript, such that I can use the whole html document as a string variable.

I have tried the following code:

var foo = "<%= render :partial => "foo" %>";

And inside _foo.html.erb, let's say I have the following:

<h1>Hello</h1>
<p>World</p>

This way will give me a syntax error in javascript because there is CRLF in the partial. But if I write code like...

<h1>Hello</h1>" +
"<p>World</p>

Now, it's not an error in javascript. I can do the latter way, but it is a disaster if the partial contains a lot of lines of code with ruby script.

Would there be any alternative way?

Thanks in advance.

Share Improve this question asked Nov 17, 2010 at 22:25 DynamicScopeDynamicScope 7051 gold badge9 silver badges26 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 15

Use escape_javascript function:

var foo = "<%= escape_javascript(render :partial => 'foo') %>";

Quick and dirty hack:

var foo = "<%= render(:partial => "foo").gsub(/[\n\r]/, ' ') %>";

This just replaces the newlines with spaces, a no-op from the point of view of an HTML parser.

However, this is a pretty fragile way to create JavaScript objects. You'll need to account for quotes in the partial that'll make your JavaScript invalid, etc. I'd suggest trying to create JavaScript templates for the HTML you want to render and populate them with JSON versions of your Models.

发布评论

评论列表(0)

  1. 暂无评论