46

Hey is there a way I can do this in 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!

0

2 Answers 2

103

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

:javascript
   var tab = #{@tab}

Take care of correctly escaping, however.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, I was sure I tried that! Thanks though!! :)
Awesome tip, thanks! I think Haml should put this note into there official docs.
-23

This is a terrible way to structure code.

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

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

In your case, I'd recommend something like:

(Haml file)

#tab= @tab

(CSS file)

#tab { display: none }

(Javascript file)

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

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

24 Comments

One thing that escaped my notice the first time: JavaScript variable names should normally begin with a lowercase letter (unless the variable refers to a constructor).
Its downvoted because you are not answering the question but stating an opinion. Sometimes I use inline js just to try something out and to save flicking between files. Later, once working, I put it in its own file. So the question can not be judged as terrible without context.
@MarnenLaibow-Koser I'll happily explain my downvote. Your response does absolutely nothing to help the OP with his question. If there were no occasion when it was ever acceptable to use inline JS, then Haml wouldn't provide filters, but it does. This question, by the way, also applies to every other filter in Haml, of which there are many. Of course inline JS is often misused, but there are much better times and places to explain that than on a non-answer to a perfectly legitimate question.
downvoted: not answer the question.
"..and you're not mixing JS and HTML" But you are mixing js and html storing data in the dom temporarily and then loading it in a js var. How is that better?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.