instance method variant=

Ruby on Rails 8.1.2

Since v4.1.16

Available in: v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

variant=(variant)

Sets the \variant for the response template.

When determining which template to render, Action View will incorporate all variants from the request. For example, if an ArticlesController#index action needs to respond to request.variant = [:ios, :turbo_native], it will render the first template file it can find in the following list:

  • app/views/articles/index.html+ios.erb

  • app/views/articles/index.html+turbo_native.erb

  • app/views/articles/index.html.erb

Variants add context to the requests that views render appropriately. Variant names are arbitrary, and can communicate anything from the request’s platform (:android, :ios, :linux, :macos, :windows) to its browser (:chrome, :edge, :firefox, :safari), to the type of user (:admin, :guest, :user).

Note: Adding many new variant templates with similarities to existing template files can make maintaining your view code more difficult.

Parameters

  • variant - a symbol name or an array of symbol names for variants used to render the response template

Examples

class ApplicationController < ActionController::Base
  before_action :determine_variants

  private
    def determine_variants
      variants = []

      # some code to determine the variant(s) to use

      variants << :ios if request.user_agent.include?("iOS")
      variants << :turbo_native if request.user_agent.include?("Turbo Native")

      request.variant = variants
    end
end

Parameters

variant req
Source
# File actionpack/lib/action_dispatch/http/mime_negotiation.rb, line 137
      def variant=(variant)
        variant = Array(variant)

        if variant.all?(Symbol)
          @variant = ActiveSupport::ArrayInquirer.new(variant)
        else
          raise ArgumentError, "request.variant must be set to a Symbol or an Array of Symbols."
        end
      end

Defined in actionpack/lib/action_dispatch/http/mime_negotiation.rb line 137 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionDispatch::Http::MimeNegotiation

Type at least 2 characters to search.

↑↓ navigate · open · esc close