:javascript haml 标签中的内联 ruby​​?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7120292/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:55:41  来源:igfitidea点击:

Inline ruby in :javascript haml tag?

javascriptruby-on-railsrubyhaml

提问by Alex Fox

Hey is there a way I can do this in haml?

嘿,有没有办法在haml中做到这一点?

:javascript
   var Tab = <%= @tab %>

I could just add a helper I guess like:

我可以添加一个我猜想的帮手:

<script>
  var Tab = '<%= @tab %>'
</script>

But it'd be nice to use HAML!

但是使用 HAML 会很好!

回答by Arnaud Le Blanc

You can use the string interpolation syntax (#{...}) :

您可以使用字符串插值语法 ( #{...}) :

:javascript
   var tab = #{@tab}

Take care of correctly escaping, however.

但是,请注意正确转义。

回答by Marnen Laibow-Koser

This is a terrible way to structure code.

这是一种糟糕的代码结构方式。

Inline JavaScript is bad enough. Inline JavaScript with ERb inside puts you straight into hell.

内联 JavaScript 已经够糟糕了。内联带有 ERb 的 JavaScript 会让你直接陷入地狱。

JavaScript should be in external static files. That way the browser can cache them, and you can use JavaScript as a real programming language.

JavaScript 应该在外部静态文件中。这样浏览器就可以缓存它们,并且您可以将 JavaScript 用作真正的编程语言。

In your case, I'd recommend something like:

在您的情况下,我建议您这样做:

(Haml file)

(哈姆勒文件)

#tab= @tab

#tab= @tab

(CSS file)

(CSS文件)

#tab { display: none }

#tab { display: none }

(Javascript file)

(Javascript文件)

var Tab = $('#tab').innerHTML();

var Tab = $('#tab').innerHTML();

That way everything stays static and maintainable, and you're not mixing JS and HTML.

这样一切都保持静态和可维护,并且您不会混合使用 JS 和 HTML。