HTML 如果从资产调用或 content_for 被转义
HTML is escaped if called from assets or content_for
我刚遇到一个问题,我的咖啡代码没有按预期处理。所以,下面的代码
#app/views/smth/edit.slim
- content_for :js_scripts
coffee:
$ ->
$("#destination-id").html("<%= escape_javascript(render :partial => 'pages') %>")
.smth-page
#some slim-html-code here
什么都不产生,但在我看来 <%= escape_javascript(render :partial => 'pages') %>
写成纯文本。不是部分的,只是带有此代码的纯文本
我觉得"OK, I move it to another file and place it to app/assets/javascript
."还有点逻辑,这样比较好看。好的,我移动了,像这样:
#app/assets/javascripts/vid/smth.coffee
class Vid.Smth
constructor: =>
$("#destination-id").html("<%= escape_javascript(render :partial => 'pages') %>")
#app/views/smth/edit.slim
- content_for :js_scripts
coffee:
$ ->
new Vid.Smth()
但没有任何改变。
谷歌搜索显示了很多没有答案和建议的问题,例如
- 用双引号替换单引号,反之亦然;
- 用
j
替换escape_javascript
;
- 使用
raw
;
- 在文件名
中使用 .js
、.erb
、.js.coffee.erb
、等
等等。 None 有帮助。
然后我想起了做同样的事情并让它发挥作用。经过几个小时的调查、复制和粘贴,我最终将这段代码部分化并从视图中呈现:
# app/views/smth/edit.slim
...
= render :partial 'test'
#app/views/smth/_test.coffee
$("#destination-id").html("<%= escape_javascript(render :partial => 'pages') %>")
成功了!部分终于渲染出来了。
所以,问题是:为什么它会这样?这是错误或功能,还是渲染规则的结果?
您不能在以 *.js 结尾的文件中使用 ruby 脚本是纯 javascript。
您应该将文件结尾更改为 *.js.erb 或 *.js.coffee.erb
并且将能够使用 rails 个助手
我意识到,我在那里做错了,所以我唯一需要做的就是javascript_tag
包装我想要渲染的JS代码。
我刚遇到一个问题,我的咖啡代码没有按预期处理。所以,下面的代码
#app/views/smth/edit.slim
- content_for :js_scripts
coffee:
$ ->
$("#destination-id").html("<%= escape_javascript(render :partial => 'pages') %>")
.smth-page
#some slim-html-code here
什么都不产生,但在我看来 <%= escape_javascript(render :partial => 'pages') %>
写成纯文本。不是部分的,只是带有此代码的纯文本
我觉得"OK, I move it to another file and place it to app/assets/javascript
."还有点逻辑,这样比较好看。好的,我移动了,像这样:
#app/assets/javascripts/vid/smth.coffee
class Vid.Smth
constructor: =>
$("#destination-id").html("<%= escape_javascript(render :partial => 'pages') %>")
#app/views/smth/edit.slim
- content_for :js_scripts
coffee:
$ ->
new Vid.Smth()
但没有任何改变。
谷歌搜索显示了很多没有答案和建议的问题,例如
- 用双引号替换单引号,反之亦然;
- 用
j
替换escape_javascript
; - 使用
raw
; - 在文件名 中使用
.js
、.erb
、.js.coffee.erb
、等
等等。 None 有帮助。
然后我想起了做同样的事情并让它发挥作用。经过几个小时的调查、复制和粘贴,我最终将这段代码部分化并从视图中呈现:
# app/views/smth/edit.slim
...
= render :partial 'test'
#app/views/smth/_test.coffee
$("#destination-id").html("<%= escape_javascript(render :partial => 'pages') %>")
成功了!部分终于渲染出来了。
所以,问题是:为什么它会这样?这是错误或功能,还是渲染规则的结果?
您不能在以 *.js 结尾的文件中使用 ruby 脚本是纯 javascript。 您应该将文件结尾更改为 *.js.erb 或 *.js.coffee.erb 并且将能够使用 rails 个助手
我意识到,我在那里做错了,所以我唯一需要做的就是javascript_tag
包装我想要渲染的JS代码。