【问题标题】:Rails Rendering namespaced template based on versionRails Rendering 基于版本的命名空间模板
【发布时间】:2022-12-09 17:38:42
【问题描述】:

我正在尝试根据我的设计版本(存储为数据库列)呈现特定的视图路径。

这个想法是,如果我的设计版本是 1,我将渲染

产品/v1/show.html.erb

如果 2 :

产品/v2/show.html.erb

为此,我在 ProductsController 中尝试过:

class ProductsController < ApplicationController
  before_action :set_view_paths
  def set_view_paths
    prepend_view_path Rails.root.join('app', 'views', 'products', "v#{current_tenant.ui_version}")
  end
end

并嵌套我的节目模板in v1/show.html.erb

但是现在我已经移动了展示模板,我得到了ProductsController#show is missing a template for request formats: text/html

我是否遗漏了有关 prepend_view_path 方法的内容?

【问题讨论】:

    标签: ruby-on-rails templates


    【解决方案1】:

    关于preprend_view_path的澄清

    https://api.rubyonrails.org/classes/ActionView/ViewPaths/ClassMethods.html

    在对它有所了解之前,您可以查看当前数组。 它应该包含app/views

    然后你的ProductsController#show会在里面寻找products/show

    我想你在这里有点困惑。

    如果您使用: prepend_view_path Rails.root.join('app', 'views', "v#{current_tenant.ui_version}") 然后您的产品文件夹将如下所示:

    app/views
      v1/products/show
      v2/products/show
    

    prepend_view_path 具有更大的全球影响力。

    product 文件夹中的实时拆分版本

    如果你想:

    app/views/products
      v1/show
      v2/show
    

    您可以覆盖渲染方法:

    class ProductsController < ApplicationController
      # actions ..
    
      private
    
      def render(*args)
        change_some_args_here = "/#{design_version_name}/#{params[:action]}"
        super(*args)
      end
    
      def design_version_name
        # implement me
      end
    end
    

    更改控制器视图路径

    还有controller_path类方法

    def self.controller_path
      "products/v1"
    end
    

    然而,如您所见,v1 在这里是静态的。 类方法意味着你不知道“实时”上下文......

    结论

    我想第二种方法符合您的需要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-08
      • 2014-11-14
      • 2014-09-27
      • 2023-03-22
      • 1970-01-01
      • 2012-09-10
      • 2017-03-21
      相关资源
      最近更新 更多