【问题标题】:symfony 5.2 gettext update po file with labels from php filessymfony 5.2 gettext 使用 php 文件中的标签更新 po 文件
【发布时间】:2021-03-31 21:16:05
【问题描述】:

我在表单类型中有翻译标签,例如:

$builder->add('island', EntityType::class, [
            'class' => Island::class,
            'choices' => $options['islands'],
            'choice_attr' => function(Island $choice) {
                // TODO move to template
                return ['data-content' => $choice->getParent()
                    ? '<span>&nbsp;&nbsp;' . $choice->getName() . '</span>'
                    : '<b>' . $choice->getName() . '</b>'
                ];
            },
            'choice_label' => 'name',
            'attr' => ['class' => 'selectpicker', 'title' => _('form.cafe.island.title')],
            'required' => true,
            'label' => false
        ])

如您所见,我尝试了传统的 _() 方式,但没有成功。 我试图在 poedit 的 po 文件中生成新标签,如下所示: php bin/console translation:update --output-format=po --force hu 任何建议或想法都非常受欢迎。 提前致谢!

【问题讨论】:

  • 您是否尝试将Symfony\Contracts\Translation\TranslatorInterface 服务注入到您的表单构建器中并调用它以使$this-&gt;translator-&gt;trans('form.cafe.island.title') 转换您的值?
  • @JeroenvanderLaan:谢谢,成功了一半。我现在可以手动将占位符添加到 po 文件中,然后翻译器进行翻译。任何想法,我怎样才能自动生成它?

标签: php forms symfony translation gettext


【解决方案1】:

最佳实践是不要在表单类型类中进行翻译。尝试将未翻译的标签放在那里,并在模板中翻译。这不能解决自动生成“.po”文件的问题,但简化了 Type 类,即。不需要注入翻译器,不需要在每个带有title属性字段的FormType类中翻译。否则以后需要在每个Type类中加入translator和translate属性。

翻译模板中的表单字段属性,需要重载内置表单模板,如Creating your Own Form Theme中所述。

在这种情况下简化流程:

  • 从用于拥有干净模板的内置模板中复制块widget_attributes。即:templates/form/my_theme.html.twig

  • 在标签form_themes中添加这个模板到config/packages/twig.yaml,即:

      twig:
          form_themes: ['form/my_theme.html.twig']
    
  • 使用extend 原始模板向此模板添加内容

      {% extends 'bootstrap_3_horizontal_layout.html.twig' %}
    
  • 和重载块widget_attributes

      {% block widget_attributes -%}
          {% if attr.title is not empty %}
              {% set attr = attr|merge({title: attr.title|trans({}, translation_domain)}) %}
          {{ parent() }}
      {%- endblock widget_attributes %}
    

通过这种方法,我们需要在一个地方进行更改并获得表单字段中所有标题属性的翻译。

正如我所说,这不会解析自动生成的“.po”文件,因为生成器无法从 PHP 类中获取翻译标签。它仅适用于模板文件。

值得注意的是,并非每个表单小部件模板都使用widget_attribute 来格式化字段属性,因此在某些情况下它需要重载特定的小部件模板块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多