How to access instance variables in CoffeeScript engine inside a Slim template

烈酒焚心 提交于 2019-11-27 06:36:10

What's happening is that "#{@user_name}" is being interpreted as CoffeeScript, not as Ruby code that's evaluated and injected into the CoffeeScript source. You're asking, "How do I inject a Ruby variable into my CoffeeScript source?"

The short answer is: Don't do this. The Rails team made an intentional decision not to support embedded CoffeeScript in templates in 3.1, because there's significant performance overhead to having to compile CoffeeScript on every request (as you'd have to do if you allowed arbitrary strings to be injected into the source).

My advice is to serve your Ruby variables separately as pure JavaScript, and then reference those variables from your CoffeeScript, e.g.:

javascript:
  user_name = "#{@user_name}";
coffee:
  $(document).ready ->
    name = user_name
    alert name

I tend to avoid inline javascript at all costs.

A nice way to store variables in your HTML, to be used from your javascript, is to use the HTML5 data-attributes. This is ideal to keep your javascript unobtrusive.

gene tsai

You could also use:

$(document).ready ->
  name = <%= JSON.generate @user_name %>
  alert name

This is because JSON is a subset of JavaScript.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!