如何将动态 Ruby 代码嵌入到 Slim 模板中的“javascript”部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5646315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to embed dynamic Ruby code to "javascript" section in Slim templates?
提问by wkang
One way:
单程:
javascript_tag do
== "var all_product_ids = #{existing_ids.to_json};"
== "var products_json = #{@filter.data.to_json};"
or:
或者:
= %Q{
var all_product_ids = #{existing_ids.to_json};
var products_json = #{@filter.data.to_json};
}
are there any better solutions for this?
有没有更好的解决方案?
采纳答案by Vlad Khomich
what i prefer to do, is to keep all the javascript in a separate file.
我更喜欢做的是将所有的 javascript 保存在一个单独的文件中。
for example, i would do it as follows(jquery):
例如,我会这样做如下(jquery):
in your layout:
在您的布局中:
...
...
<body data-product-ids="<%= existing_ids.to_json %>"
data-products-json="<%= @filter.data.to_json %>">
.. in js:
.. 在 js 中:
// create your application namespace
$.myapp = {};
$.myapp.allProductIds = $.parseJSON( $('body').attr('data-product-ids') );
$.myapp.products = $.parseJSON( $('body').attr('data-products-json') );
so, you'll then use it in js like so:
所以,你会像这样在 js 中使用它:
$.myapp.allProductIds
回答by stonean
In Slim
在苗条
javascript:
var all_product_ids = "#{existing_ids.to_json}";
var products_json = "#{@filter.data.to_json}";
回答by lidaobing
javascript:
var all_product_ids = #{raw existing_ids.to_json};
var products_json = #{raw @filter.data.to_json};
回答by Karthik M
From https://github.com/slim-template/slimText Interpolation paragraph
来自https://github.com/slim-template/slim文本插值段
SLIM escapes HTML by default. To avoid the same use #{{content}}for #{content}
SLIM 默认转义 HTML。为了避免同样使用#{{内容}}的#{}内容
回答by Marvin Alejandro Herrera
I had a similar problem with this. Using the code that others have provided didn't work for me because slim was html escaping my variable. I ended up using Gon. This one is for Sinatra, but they have a gem for Rails as well. Hope it helps others having similar problems.
我有一个类似的问题。使用其他人提供的代码对我不起作用,因为 slim 是 html 转义我的变量。我最终使用了Gon。这个是给 Sinatra 的,但他们也有一个针对 Rails 的宝石。希望它可以帮助其他有类似问题的人。
回答by Lane
create a _your_erb_file_contain_javascript_code.erbfirst
创建_your_erb_file_contain_javascript_code.erb第一个
And then in your slim file javascript:part:
然后在你的瘦文件javascript:部分:
#{ conditions ? (render 'your_erb_file_contain_javascript_code') : nil}
回答by Lane
javascript:
var isAdmin = "#{current_user.admin? ? 1 : 0}";

