编写依赖于另一个标签的twig标签

I'm trying to create a twig tag that can be used as follows:

{% set_domain "zip-recipes" %}
...
...
{% trans "Ingredients" %}
...
{% trans "Ingredients" %}

trans tag would required domain set in set_domain tag.

I'm created the node and parser for set_domain to add the domain to $context:

class Project_TransDomain_Node extends \Twig_Node
{
    public function __construct($domain, $line, $tag = null)
    {
        parent::__construct(array(), array('domain' => $domain), $line, $tag);
    }

    public function compile(\Twig_Compiler $compiler)
    {
        $compiler
            ->addDebugInfo($this)
            ->write('$context[\'trans_domain\'] = "' . $this->getAttribute('domain') . '"')
            ->raw(";
")
        ;
    }
}

class TransDomain_TokenParser extends \Twig_TokenParser
{
    public function parse(\Twig_Token $token)
    {
        $parser = $this->parser;
        $stream = $parser->getStream();

        $domain = $stream->expect(\Twig_Token::STRING_TYPE)->getValue();
        $stream->expect(\Twig_Token::BLOCK_END_TYPE);

        return new Project_TransDomain_Node($domain, $token->getLine(), $this->getTag());
    }

    public function getTag()
    {
        return 'set_domain';
    }
}

However, I'm not sure how to access that in the node for trans.

I tried this but it doesn't evaluate the $context['trans_domain']:

class Project_Trans_Node extends \Twig_Node
{
    public function __construct($string, $line, $tag = null)
    {
        parent::__construct(array(), array('string' => $string), $line, $tag);
    }

    public function compile(\Twig_Compiler $compiler)
    {
        $string = $this->getAttribute('string');
        $domainExpr = $context['trans_domain'];

        $compiler
            ->addDebugInfo($this)
            ->write("echo __('${string}','")
            ->repr('$context["trans_domain"]')
            ->raw("'")
            ->raw(";
")
        ;
    }
}

Symfony already has a trans_default_domain tag (since 2.1), just use that.

You can set the translation domain for an entire Twig template with a single tag:

{% trans_default_domain "app" %}

Note that this only influences the current template, not any "included" template (in order to avoid side effects).