rails i18n - translating text with links inside

后端 未结 9 732
名媛妹妹
名媛妹妹 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:44

    I wanted a bit more flexibility than just adding links to flash messages from YAML files (for example the logged in username etc.) so instead I wanted to use ERB notation in the string.

    As I am using bootstrap_flash so I modified the helper code as follows to decode the ERB strings before displaying:

    require 'erb'
    
    module BootstrapFlashHelper
      ALERT_TYPES = [:error, :info, :success, :warning] unless const_defined?(:ALERT_TYPES)
    
      def bootstrap_flash
        flash_messages = []
        flash.each do |type, message|
          # Skip empty messages, e.g. for devise messages set to nothing in a locale file.
          next if message.blank?
    
          type = type.to_sym
          type = :success if type == :notice
          type = :error   if type == :alert
          next unless ALERT_TYPES.include?(type)
    
          Array(message).each do |msg|
            begin
              msg = ERB.new(msg).result(binding) if msg
            rescue Exception=>e
              puts e.message
              puts e.backtrace
            end
            text = content_tag(:div,
                               content_tag(:button, raw("×"), :class => "close", "data-dismiss" => "alert") +
                               msg.html_safe, :class => "alert fade in alert-#{type}")
            flash_messages << text if msg
          end
        end
        flash_messages.join("\n").html_safe
      end
    end
    

    It is then possible to use strings like the following (using devise):

    signed_in: "Welcome back <%= current_user.first_name %>! <%= link_to \"Click here\", account_path %> for your account."
    

    This may not work for all situations and there may be an argument that code and string definitions should not be mixed (especially from a DRY perspective), but this seems to work well for me. The code should be adaptable for many other situations, the important bits being the following:

    require 'erb'
    
    ....
    
            begin
              msg = ERB.new(msg).result(binding) if msg
            rescue Exception=>e
              puts e.message
              puts e.backtrace
            end
    
    0 讨论(0)
  • 2020-11-30 21:50

    Separating text and link in locale.yml file works for a while but with longer text those are hard to translate and maintain as the link is in separate translation-item (as in Simones answer). If you start having many strings/translations with links you can dry it a bit more.

    I made one helper in my application_helper.rb:

    # Converts
    # "string with __link__ in the middle." to
    # "string with #{link_to('link', link_url, link_options)} in the middle."
    def string_with_link(str, link_url, link_options = {})
      match = str.match(/__([^_]{2,30})__/)
      if !match.blank?
        raw($` + link_to($1, link_url, link_options) + $')
      else
        raise "string_with_link: No place for __link__ given in #{str}" if Rails.env.test?
        nil
      end
    end
    

    In my en.yml:

    log_in_message: "Already signed up? __Log in!__"
    

    And in my views:

    <p><%= string_with_link(t('.log_in_message'), login_path) %></p>
    

    This way it's easier to translate messages as also the link text is clearly defined in the locale.yml-files.

    0 讨论(0)
  • 2020-11-30 21:50

    In en.yml

    registration:
        terms:
          text: "I do agree with the terms and conditions: %{gtc} / %{stc}"
          gtc: "GTC"
          stc: "STC"
    

    In de.yml

    registration:
        terms:
          text: "Ich stimme den Geschäfts- und Nutzungsbedingungen zu: %{gtc} / %{stc}"
          gtc: "AGB"
          stc: "ANB"
    

    in new.html.erb [assumed]

    <%= t(
       'registration.terms.text',
        gtc:  link_to(t('registration.terms.gtc'),  terms_and_conditions_home_index_url + "?tab=gtc"),
        stc: link_to(t('registration.terms.stc'), terms_and_conditions_home_index_url + "?tab=stc")
     ).html_safe %>
    
    0 讨论(0)
提交回复
热议问题