Skip to content
This repository has been archived by the owner on Jun 10, 2018. It is now read-only.

Client-side inline CoffeeScript #17

Closed
aseemk opened this issue May 11, 2011 · 3 comments
Closed

Client-side inline CoffeeScript #17

aseemk opened this issue May 11, 2011 · 3 comments

Comments

@aseemk
Copy link

aseemk commented May 11, 2011

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

@gasi
Copy link

gasi commented May 12, 2011

+1 Great idea!

@aseemk
Copy link
Author

aseemk commented May 13, 2011

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.

@sstephenson
Copy link
Owner

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants