haml/javascript/erb 转义
我遇到了一个奇怪的情况,但情况是这样的:
# a HAML file
:javascript
#{ if session[:view].blank?
"$.ajax({
url: 'url_for params.merge(:action => 'index')',
dataType: 'script'})"
else
"$.ajax({
url: 'url_for companies_url',
dataType: 'script'})"
end }
所以这基本上是将 javascript 嵌套在 ruby 中,嵌套在 javascript 中,嵌套在 HAML 中。它不起作用,因为我的引号嵌套不正确。
- 我想有更好的方法来做到这一点。有什么想法吗?
- 上面发生的 ajax 将一些部分渲染到当前视图中并更改会话变量。如何更新此 javascript,使其在新会话[:view] 下正确运行?
I have an odd situation, but here it is:
# a HAML file
:javascript
#{ if session[:view].blank?
"$.ajax({
url: 'url_for params.merge(:action => 'index')',
dataType: 'script'})"
else
"$.ajax({
url: 'url_for companies_url',
dataType: 'script'})"
end }
So this is basically nesting javascript inside ruby, inside javascript, inside HAML. It doesn't work because I've got improper nesting of quotes.
- I imagine there's a better way to do this. Any thoughts?
- The ajax happening above renders some partials into the current view and changes the session variable. How can I update this javascript so it behaves correctly given the new session[:view]?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 ERB 和辅助方法。它干净了很多:
Use ERB and a helper method. It's a lot cleaner:
在我看来,你不需要切换到ERB,但辅助方法很好。我会将 URL 放入页面呈现的标签中。通常我会在锚标记的 data-href 属性中执行此操作,以实现不显眼的 javascript。例如:
然后:
那么您的部分需要做的就是重新渲染 link_to ,这将重新生成正确的 url_for_ajax_call 。
显然,这种方法需要做更多的工作,因为您需要向链接,您需要停止实际点击该链接(http://api.jquery.com/event.preventDefault/)。但是没有必要为单个文件切换到 ERB,您可以处理关闭 javascript 的用户,它将解决您的第二个问题。
In my opinion, you don't need to switch to ERB but the helper method is good. I'd put the URL into a tag that the page renders. Usually I do this in an anchor tag's data-href attribute for unobtrusive javascript. For example:
Then:
Then all your partial needs to do is re-render the link_to which will regenerate the correct url_for_ajax_call.
Obviously, this way is a little more work as you'll need to add a click event handler to the link and you'll need to stop the actual clicking of the link from occurring (http://api.jquery.com/event.preventDefault/). But there's no need to switch to ERB for a single file, you can handle users that turn off javascript, and it'll solve your second question.
我能找到的使用 haml 执行此类操作的最佳方法是将 javascript 作为文本写入 %script 块内。所以你的代码将变成:
作为奖励,你现在甚至可以进行 ruby 插值:
Best way I could find to do this kind of things with haml is to write javascript as text inside a %script bloc. So your code would become:
as a bonus you can even do ruby interpolation now: