开发者

How to use partial in views with different alias MIME?

开发者 https://www.devze.com 2023-01-06 06:49 出处:网络
Im using 2 different sets of views for 2 different user\'s roles. Im using register_alias : Mime::Type.register_alias \"text/html\", :basic

Im using 2 different sets of views for 2 different user's roles. Im using register_alias :

Mime::Type.register_alias "text/html", :basic

in the controller:

class SomeController < ApplicationController
  def index
    # …
    respond_to do |format|
      format.html  # 开发者_运维知识库index.html.erb (advance)
      format.basic # index.basic.erb
    end
  end
end

In some case I have to use the same code in both views, then I would use a Partial, but because of the MIME alias, I have to use 2 identical partials: my_partial.html.erb and my_partial.basic.erb

I think there is a solution to DRY the code and use only a partial.

Do you have some solutions ?

thank you, Alessandro


Old Answer:

I probably tried 50 different things until I figured out the right way of writing the partial once, but it was worth it because it's super simple:

Inside your index view, you normally do:

<%= render "my_partial" %>

This implicitly gets mapped to the partial corresponding to the Mime you requested, so it implies having two partial implementations. If you want a DRY partial, simply explicitly specify the format:

<%= render "my_partial.html" %>

As an added bonus of this observation, if your responds_to block of code is really just to switch based on the format and has no logic inside it, you can entirely remove that block of code and things still work implicitly.

Rails 3.2 update:

Rails has deprecated support for the above and support has been completely removed in the latest version of Rails. The following is the correct way as of Rails 3.2:

<%= render :partial => "my_partial", :formats => [:html] %>
0

精彩评论

暂无评论...
验证码 换一张
取 消