如何检查 Twig/Symfony2 中是否存在翻译项? [英] How to check if a translation item exists in Twig/Symfony2?

查看:27
本文介绍了如何检查 Twig/Symfony2 中是否存在翻译项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用于打印侧边栏项目的宏.每个 title 属性都是为了寻找 'tip' 而构建的.~ route messages.it.yml 中的项目.

Here is my macro for printing a sidebar item. Each title atttribute is build looking for 'tip.' ~ route item in messages.it.yml.

即使 trans 项不存在 Twig 也总是返回传递给 trans 过滤器的字符串.例如:

Even if the trans item does not exist Twig always return the string passed to trans filter. For example:

tip:
    dashboard: Dashboard

模板:

{% _self.sideitem('dashboard', 'home') %} // <a title="Dashboard">...
{% _self.sideitem('fail', 'home') %}      // <a title="tip.fail">...

{% macro sideitem(route, icon) %}
    {% set active = (route == app.request.get('_route')) %}
    {% set icon = icon ? 'icon-' ~ icon ~ (active ? ' icon-white' : '') : '' %}

    <li class="{{ active ? 'active' : '' }}">
        <a href="{{ path(route) }}" title="{{ ('tip.' ~ route)|trans }}">
            <i class="{{ icon }}"></i> {{ ('nav.' ~ route)|trans }}
        </a>
    </li>
{% endmacro %}

如何在实际打印之前检查是否存在跨项目?

编辑:一个残酷的解决方法可能是(代码未经测试):

EDIT: a brutal workaround could be (code not tested):

<li class="{{ active ? 'active' : '' }}">
    {% set look    = ('tip.' ~ route) %}
    {% set foreign = look|trans %}
    {% set has     = not(look == foreign) %}

    <a href="{{ path(route) }}" {{ not has ? '' : 'title="' ~ foreign ~ '"'  }} >
        <i class="{{ icon }}"></i> {{ ('nav.' ~ route)|trans }}
    </a>
 </li>

推荐答案

我想出的解决方案是这样的:

The solution I came up with was this one:

{% if "#{var}.something"|trans != "#{var}.something" %}

这只是检查翻译键的结果是否与翻译键本身不同.如果键没有翻译,trans"过滤器返回翻译键.

This just checks if the result of the translation key is different from the translation key itself. If a key has no translation, the "trans" filter returns the translation key.

这篇关于如何检查 Twig/Symfony2 中是否存在翻译项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆