使用键进行symfony翻译

使用键进行symfony翻译

本文介绍了使用键进行symfony翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想翻译symfony中的内容,我将按照书中的描述使用翻译器:

If I want to translate content in symfony, I will use the translator as it is described in the book:

$translated = $this->get('translator')->trans('Symfony2 is great');

但是,如果该翻译已经存在于数据库中,我该如何访问呢?

But, if this translations are already existing in a database, how can I access this?

数据库看起来像

ID | locale | type   | field            | content
 1 |   en   | message| staff.delete     | delete this user?

我必须告诉翻译者他在哪里可以得到翻译信息.您能帮我写一个好教程或给个窍门吗?

I wil have to tell the translator where he can get the translation information. Cann you help me with a good tutorial or tipps an tricks?

推荐答案

根据文档,您需要注册服务才能从数据库等其他来源加载翻译

According to docs you need to register a service in order to load translations from other source like from database

我做了什么,我有一个翻译包,我的翻译实体驻留在其中,因此我已在config.yml中注册了一项服务,并通过了学说管理器@doctrine.orm.entity_manager以便从实体中获取数据

What i have done,i have a translation bundle where my translation entity resides so i have registered a service in config.yml and passed doctrine manager @doctrine.orm.entity_manager in order to get data from entity

services:

    translation.loader.db:
        class: Namespace\TranslationBundle\Loader\DBLoader
        arguments: [@doctrine.orm.entity_manager]
        tags:
            - { name: translation.loader, alias: db}

DBLoader类中,我已经从数据库和集合中获取了翻译,如docs translation.loader

In DBLoader class i have fetched translations from database and sets as mentioned in docs translation.loader

我的加载程序类

namespace YourNamespace\TranslationBundle\Loader;

use Symfony\Component\Translation\Loader\LoaderInterface;
use Symfony\Component\Translation\MessageCatalogue;
use Doctrine\ORM\EntityManager;

class DBLoader implements LoaderInterface{
    private $transaltionRepository;
    private $languageRepository;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager){

        $this->transaltionRepository = $entityManager->getRepository("YourNamespaceTranslationBundle:LanguageTranslation");
        $this->languageRepository = $entityManager->getRepository("YourNamespaceTranslationBundle:Language");
    }

    function load($resource, $locale, $domain = 'messages'){
        //Load on the db for the specified local

        $language = $this->languageRepository->findOneBy( array('locale' => $locale));

        $translations = $this->transaltionRepository->getTranslations($language, $domain);

        $catalogue = new MessageCatalogue($locale);


        /**@var $translation YourNamespace\TranslationBundle\Entity\LanguageTranslation */
        foreach($translations as $translation){
            $catalogue->set($translation->getLanguageToken(), $translation->getTranslation(), $domain);
        }
        return $catalogue;
    }
}

这篇关于使用键进行symfony翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:20