简体   繁体   中英

Can I use Coffeescript and ERB in the same file and keep readable indentation?

In Rails, I have a Coffeescript file in my views that gets rendered as the response to an AJAX request.

If I have some ERB control logic using <% %> , Id' like to be able to indent everything logically like I would in an HTML view:

exampleFunction = ->
  <% if condition %>
    alert("condition met!")
  <% else %>
    alert("condition not met!")
  <% end %>

But this usually means the Coffeescript throws indentation errors and won't compile. (The example I just gave might not fail, I haven't bothered to check, but it happens all the time in less contrived cases.)

So I have to indent things in this rather unwieldy way:

exampleFunction = ->
  <% if condition %>
  alert("condition met!")
  <% else %>
  alert("condition not met!")
  <% end %>

Is there any other way around this? Can I get Coffeescript and ERB to play nicely with eachother and allow for more readable indentation?

This doesn't quite answer the question, but I'd suggest setting variables using ERB, and then checking those in the logic instead - for example:

condition = <%= condition.to_s %>

exampleFunction = ->
    if condition
        alert("condition met!")
    else
        alert("condition not met!")

This will mean that all of the code is available when debugging/running, and makes the ERB template a lot easier to manage with regards to indentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM