简体   繁体   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?

I want my page to render some Javascript, conditional on a variable from the Rails environment.我希望我的页面呈现一些 Javascript,以 Rails 环境中的变量为条件。 I must have everything in this one file, because of other build tooling constraints.由于其他构建工具的限制,我必须在这个文件中包含所有内容。

Eseentially I am trying to get this working:本质上,我试图让这个工作:

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

However, when I try this, I get errors that < is not a valid character.但是,当我尝试此操作时,我收到<不是有效字符的错误。

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

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

Also, this question might be useful: ruby inside javascript block [slim template]此外,这个问题可能很有用: javascript 块内的 ruby [slim template]

you cannot use <%... %> in your javascript您不能在 javascript 中使用<%... %>

If you want to use rails data, try ei如果你想使用 rails 数据,试试 ei

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

Another way, you should be use ajax( it was mean your_action.js.slim ), see ie bellow另一种方式,你应该使用 ajax(意思是 your_action.js.slim ),见下面

create.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.

相关问题 我如何使用javascript将文件的一部分包含在另一个文件中 - how can i include part of a file in another file with javascript 如何使用slim来引用javascript文件 - How can I reference a javascript file with slim 如何在React中的某些HTML中间有条件地包含标记 - How do I conditionally include a tag in the middle of some HTML in React 使用Komodo Editor 8.5,如何将一个具有javascript函数链接页面的项目创建为较大项目的一部分? - Using Komodo Editor 8.5, How can I create a project that has a linked page for javascript functions as part of a larger project? 在HTML / JavaScript文件中,如何选择要包含的数据文件? - In an HTML/JavaScript file, how can I select a data file to include? 如何在JavaScript中有条件地包含脚本文件? - How do I conditionally include a script file in JavaScript? 如何将我的 JavaScript 文件包含到 HTML 页面中? - How can I include my JavaScript file into an HTML page? 如何有条件地包含远程JavaScript文件? - How to include a remote JavaScript file conditionally? 如何在Rails 4中的javascript中包含ruby变量? - How do I include ruby variables in javascript in Rails 4? 如何在Ruby on Rails项目中使用JavaScript解码HTML实体 - How to decode HTML entities in JavaScript using in a Ruby on Rails project
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM