【问题标题】:Embedding YAML alias within YAML string在 YAML 字符串中嵌入 YAML 别名
【发布时间】:2020-01-13 17:06:21
【问题描述】:

我正在尝试在我的 YAML 文件中声明一个别名,并稍后在字符串中使用它。例如,我声明:

en:
  support_email: &support_email "helpme@foo.com"
  support_text: "Having a problem? Reach out to <a href="*support_email">*support_email</a>"

并希望 en.support_text 评估为 Having a problem? Reach out to &lt;a href="helpme@foo.com"&gt;helpme@foo.com&lt;/a&gt;

有没有办法做到这一点?就上下文而言,这是在一个 RoR 项目中。

感谢您的帮助!

【问题讨论】:

    标签: ruby-on-rails ruby yaml


    【解决方案1】:

    您不能对 YAML 本身执行此操作,因为 specification 特异性排除了此:

    7.1。别名节点

    先前serialized 节点的后续出现是 presented 作为别名节点node 的第一次出现 必须用anchor 标记以允许后续出现 presented 作为别名节点。

    别名节点由“*”指示符表示。别名指的是 最近的node 具有相同的anchor。它是一个 别名节点使用以前没有的 anchor 时出错 发生在document。指定一个不是错误的 anchor 未被任何别名节点使用。

    请注意,别名节点不得指定任何propertiescontent,因为这些已在第一次出现时指定 的node

    示例 7.1。别名节点

    First occurrence: &anchor Foo
    Second occurrence: *anchor
    Override anchor: &anchor Bar
    Reuse anchor: *anchor
    

    但是,您可以使用variable interpolation with I18n。以你的例子为例:

    en:
      support_email: 'helpme@foo.com'
      support_text: 'Having a problem? Reach out to <a href="mailto:%{support_email}">%{support_email}</a>'
    

    那么在你看来:

    <%= t('support_text', support_email: t('support_email')) %>
    

    请注意,上面没有标记为 HTML 安全,可以通过 adding the _html suffix changing the last element to html 完成。或者,您可以自己在结果上调用.html_safe,或者使用&lt;%== ... %&gt;(而不是&lt;%= ... %&gt;)或&lt;%= raw ... %&gt;作为原始内容输入。

    如果您想更动态地分配变量,请考虑更改 YAML 文件的结构。

    en:
      support:
        constants:
          message: 'Having a problem?'
          phone: '0123456789'
          email: 'helpme@foo.com'
        help_messages:
          phone:
            text: '%{message} Call us on %{phone}.'
            html: '%{message} Call us on %{phone}.'
          email:
            text: '%{message} Reach out to %{email}.'
            html: '%{message} Reach out to <a href="mailto:%{email}">%{email}</a>.'
    

    现在做这样的事情:

    <% vars = t('support.constants') %>
    <%= t('support.help_messages.email.html', vars) %>
    

    您也可以将其移至您自己的助手:

    def t_with_constants(base, path, options = {})
      options = t("#{base}.constants").deep_merge(options)
      t("#{base}.#{path}", options)
    end
    

    允许您使用:

    <%= t_with_constants('support', 'help_messages.email.html') %>
    

    请注意,如果您不在视图或助手中,您可能需要改用I18n.t。不会有ActionView::Helpers::TranslationHelper#t 提供的生活质量改进(例如将字符串标记为 HTML 安全)。

    当然,您可以对此做出自己的改变,但我建议您查看I18n guideActionView::Helpers::TranslationHelper#translate 下的文档以获取更多信息。

    【讨论】:

    • 超级有用——正是我需要的。非常感谢!
    猜你喜欢
    • 2012-11-22
    • 2020-04-30
    • 2021-06-15
    • 1970-01-01
    • 2021-08-28
    • 2010-10-17
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    相关资源
    最近更新 更多