rails i18n - translating text with links inside

后端 未结 9 789
名媛妹妹
名媛妹妹 2020-11-30 21:05

I\'d like to i18n a text that looks like this:

Already signed up? Log in!

Note that there is a link on the text. On this example

9条回答
  •  独厮守ぢ
    2020-11-30 21:35

    We had the following:

    module I18nHelpers
      def translate key, options={}, &block
        s = super key, options  # Default translation
        if block_given?
          String.new(ERB::Util.html_escape(s)).gsub(/%\|([^\|]*)\|/){
            capture($1, &block)  # Pass in what's between the markers
          }.html_safe
        else
          s
        end
      end
      alias :t :translate
    end
    

    or more explicitly:

    module I18nHelpers
    
      # Allows an I18n to include the special %|something| marker.
      # "something" will then be passed in to the given block, which
      # can generate whatever HTML is needed.
      #
      # Normal and _html keys are supported.
      #
      # Multiples are ok
      #
      #     mykey:  "Click %|here| and %|there|"
      #
      # Nesting should work too.
      #
      def translate key, options={}, &block
    
        s = super key, options  # Default translation
    
        if block_given?
    
          # Escape if not already raw HTML (html_escape won't escape if already html_safe)
          s = ERB::Util.html_escape(s)
    
          # ActiveSupport::SafeBuffer#gsub broken, so convert to String.
          # See https://github.com/rails/rails/issues/1555
          s = String.new(s)
    
          # Find the %|| pattern to substitute, then replace it with the block capture
          s = s.gsub /%\|([^\|]*)\|/ do
            capture($1, &block)  # Pass in what's between the markers
          end
    
          # Mark as html_safe going out
          s = s.html_safe
        end
    
        s
      end
      alias :t :translate
    
    
    end
    

    then in ApplicationController.rb just

    class ApplicationController < ActionController::Base
      helper I18nHelpers
    

    Given a key in the en.yml file like

    mykey: "Click %|here|!"
    

    can be used in ERB as

    <%= t '.mykey' do |text| %>
      <%= link_to text, 'http://foo.com' %>
    <% end %>
    

    should generate

    Click here!
    

提交回复
热议问题