3

I'm using a standalone Twig instance in a custom application, but parameters (context) passed to the template seem to be surprisingly ignored.

Executing the following code results in this error :

Fatal error: Uncaught exception 'Twig_Error_Runtime' with message 'Variable " msg" does not exist in "hello.twig" (...)

test.php

$options = array(
      'charset' => 'utf-8',
      'debug' => true,
      'strict_variables' => true,
);

$env = new Twig_Environment(new \Twig_Loader_Filesystem(getcwd()), $options);

return $env->render("hello.twig", array('msg' => 'World'));
// I also tried this
return $env->loadTemplate("hello.twig")->render(array('msg' => 'World'));

hello.twig

Hello {{ msg }}

Registering a global variable ( $env->addGlobal('msg', 'Everybody') ) is no more successful.

Did I miss something or should it be working?

Profet
  • 944
  • 1
  • 15
  • 22
  • Why there can be a comma after last element in $options? – Joe Horn Aug 30 '15 at 20:52
  • 2
    I have a fourth (commented) line in my code that I removed in this post. However, PHP doesn't see any difference whether the last item of an array is followed by a coma :) – Profet Aug 30 '15 at 20:59
  • I can't seem to duplicate your error. Post the rest of your code. – ElefantPhace Aug 30 '15 at 21:38
  • 2
    By the look of your error `" msg"` you have have a fake space character in your template. try deleting and retyping `{{ msg }}` – ElefantPhace Aug 30 '15 at 21:42
  • i can't reproduce your problem... which version of twig are you using? – Matteo Aug 31 '15 at 05:39
  • ElefantPhace was right, my text editor was secretly adding unsecable spaces after {{ and ~ characters. It's working fine if I replace them with a normal space, thanks :) – Profet Aug 31 '15 at 07:14

1 Answers1

0

As ElefantPhace pointed out, an unsecable space was present after the {{ in the twig template, resulting in a wrong variable name. Replacing it by a regular space character solved the problem :)

Profet
  • 944
  • 1
  • 15
  • 22