簡體   English   中英

作為更大的 Ruby on Rails 項目的一部分,我如何有條件地在 html.slim 文件中包含一些 Javascript?

[英]How can I conditionally include some Javascript in an html.slim file, as part of a larger Ruby on Rails project?

我希望我的頁面呈現一些 Javascript,以 Rails 環境中的變量為條件。 由於其他構建工具的限制,我必須在這個文件中包含所有內容。

本質上,我試圖讓這個工作:

= javascript:
     console.log('My javascript goes in this area....');
     <% if myCondition %>
          console.log('Render the JS in here is myCondition is true')
     <%end>

但是,當我嘗試此操作時,我收到<不是有效字符的錯誤。

 javascript:
   console.log('My javascript goes in this area....');

 - if myCondition
   javascript:
      console.log('Render the JS in here is myCondition is true')

此外,這個問題可能很有用: javascript 塊內的 ruby [slim template]

您不能在 javascript 中使用<%... %>

如果你想使用 rails 數據,試試 ei

var form_id = "form"+ #{{@product.id.to_json}};

另一種方式,你應該使用 ajax(意思是 your_action.js.slim ),見下面

創建.js.slim

- if @product.errors.present?
  | toastr["error"]("#{@product.errors.full_messages[0]}");
- else
  | toastr["success"]("Created successfully!");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM