把手/胡子与铁轨url_for

时间:2011-11-03 19:11:20

标签: ruby-on-rails handlebars.js

我正在尝试使用{{id}}作为其中一个参数的命名路由,允许Handlebars使用渲染的内容。 url_for正在转义参数,因此生成的网址包含%7B%7Bid%7D%7D。我已经尝试在调用中添加:escape => false,但它没有效果。

的routes.rb

resources :rants, :except => [:show] do
  post '/votes/:vote', :controller => 'votes', :action => 'create', :as => 'vote'
end

index.haml

%script{:id => 'vote_template', :type => 'text/x-handlebars-template'}
  .votes
    = link_to 'up', rant_vote_path(:rant_id => '{{id}}', :vote => 'up')
    %span {{votes}}
    = link_to 'down', rant_vote_path(:rant_id => '{{id}}', :vote => 'down')

的application.js

var vote_template =  Handlebars.compile($('#vote_template').html());

输出

<script id="vote_template" type="text/x-handlebars-template">
  <div class='votes'>
    <a href="/rants/%7B%7Bid%7D%7D/votes/up">up</a>
    <span>{{votes}}</span>
    <a href="/rants/%7B%7Bid%7D%7D/votes/down">down</a>
  </div>
</script>

为了便于阅读,我简化了这个例子,但问题仍然存在;有没有办法使用{{ }}作为参数的命名路由?我知道我可以做link_to 'up', '/rants/{{id}}/votes/up'所以请不要提供答案。

2 个答案:

答案 0 :(得分:2)

问题是小胡子字符在URL中无效并且正在被转义。我建议创建一个包装器。

def handlebar_path(helper, arguments={})
  send("#{helper}_path", arguments).gsub(/%7B%7B(.+)%7D%7D/) do
    "{{#{$1}}}"
  end
end

handlebar_path :rant_vote, :rant_id => '{{id}}', :vote => 'up'

答案 1 :(得分:0)

我最终只是覆盖url_for来处理自定义参数:

module TemplateHelper

  def url_for(*args)
    options = args.extract_options!
    return super unless options.present?

    handle = options.delete(:handlebars)
    url = super(*(args.push(options)))
    handle ? url.gsub(/%7B%7B(.+)%7D%7D/){|m| "{{#{$1}}}"} : url
  end

end

现在,调用named_url(:id => '{{id}}', :handlebars => true)可以按预期工作。

相关问题