Client-side inline CoffeeScript
aseemk opened this issue · 3 comments
Just an idea / feature request:
In general, you want client-side JavaScript in a separate, external file -- good for cacheability, separation of concerns, etc.
There are occasions though where you want a snippet of inline JavaScript in a <script>
block. Maybe it's something page-specific, or something dynamically generated, or maybe this is just a quick prototype.
It would be super awesome and convenient if I could write that code in CoffeeScript, e.g. via <script type="text/coffeescript">
, and have Eco automatically compile that to JavaScript. <3
+1 Great idea!
Actually, <script type="text/coffeescript">
is both verbose and probably dangerous/tricky/non-trivial since it'd be part of regular HTML markup. So maybe something like:
<% _script: %>
# This block of CoffeeScript will get compiled to JS and
# sent back in a `<script>` block.
console.log 'This will get logged in the browser.'
<% end %>
Not sure about _script
, but I'm thinking some means similar to this.
You can implement this with a helper method.
CoffeeScript = require 'coffee-script'
eco = require 'eco'
template = """
<h1>Hello world</h1>
<%= @coffeeScriptTag -> %>
console.log 'Hello world'
<% end %>
"""
console.log eco.render template,
coffeeScriptTag: (yield) ->
script = CoffeeScript.compile yield()
@safe "<script type=\"text/javascript\">#{script}</script>"
Produces:
<h1>Hello world</h1>
<script type="text/javascript">(function() {
console.log('Hello world');
}).call(this);
</script>
Closing the ticket.