3

I have some variables in twig-templates, so think use global scope for it.

config.yml
twig:
 globals:
  varA: "@wf.autoload.getA"
  varB: "@wf.autoload.getB"

In service yml I have:

services.yml
 wf.autoload:
  class: Scope\WfBundle\WfAutoloadService
  arguments: ["@doctrine.orm.entity_manager"]

WfAutoloadService class have public function for getting variables

    class WfAutloadService {
    ...
    public function getA(){
    return ...;
    }

    public function getB(){
    return ...
    }
    ...
    }

My idea doesn't work. Method of @=service(wf.autoload).getA() also doesn't work.

Is it possible? Or it bad idea and bad practice?

Thanks

5
  • Maybe I must use another services, f.e wf.autoload.getA and call method in it?
    – Salavat
    Jul 26, 2016 at 13:13
  • 2
    it is better to create twig extension to define this functions (getA, getB)
    – Goku
    Jul 26, 2016 at 13:16
  • 1
    Do you want to access the twig global variables in controller?
    – Alok Patel
    Jul 26, 2016 at 13:18
  • @DOZ and then use them in templates? I would use only Variable as such as I set them for render.
    – Salavat
    Jul 26, 2016 at 13:19
  • @AlokPatel, nope. in twig-templates. For constructions such as {{ foreach A in varA }}. Now I do it so {{ foreach A in varA.getA }}
    – Salavat
    Jul 26, 2016 at 13:20

2 Answers 2

5

If getA() and getB() returns object, you can use a factory when configuring your service:

services:
    wf.autoload:
        class: Scope\WfBundle\WfAutoloadService
        arguments: ["@doctrine.orm.entity_manager"]
    wf.autoload.getA:
        class:   A
        factory: ["@wf.autoload", getA]

And set the global twig:

twig:
 globals:
  varA: "@wf.autoload.getA"
1
  • That's what I need! Thank you!
    – Salavat
    Jul 26, 2016 at 14:06
1

I you want to use this functions in many twig templates you can create a twig extension

For example :

class MyExtensions extends \Twig_Extension
{
    public function getFunctions()
    {
            return array(
                'getA' => new \Twig_Function_Method($this, 'getA', array('is_safe' => array('html')))
            );
    }

    public function getA() // you can if you want pass parameters
    {
       //your code

       return ...
    }
}

Declare it as service :

myextensions.twig_extension:
      class: Project\YourBundle\Twig\MyExtensions
      public: false
      tags:
          - { name: twig.extension }

And call it in yours twig template :

{{ getA() }}
1
  • Thank you, but it something another that I want.
    – Salavat
    Jul 26, 2016 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.