Handles / Mustache with rails url_for

I am trying to use a named route with {{id}} as one of the parameters, allowing processed content to consume Handlebars. url_for speeds up the parameter, so the resulting URL contains %7B%7Bid%7D%7D . I tried adding :escape => false to the call, but it has no effect.

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()); 

Output

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

I simplified the example for readability, but the question remains the same; is there any way to use a named route with {{ }} as a parameter? I understand that I can just do link_to 'up', '/rants/{{id}}/votes/up' , so please do not report this as an answer.

+4
source share
2 answers

In the end, I just redefined url_for to handle the custom parameter:

 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 

So, calling named_url(:id => '{{id}}', :handlebars => true) works as you expected.

0
source

The problem is that mustache characters are invalid in the URLs and are reset. I would recommend creating a wrapper.

 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' 
+2
source

Source: https://habr.com/ru/post/1379538/


All Articles