Twig Development

From OpenEMR Project Wiki

Twig is the preferred templating method for OpenEMR. While legacy code is still found throughout the codebase, new pages and large refactoring efforts should use Twig.

The TwigContainer

A custome TwigContainer exists to make working with Twig easier. To get started include the following in your page:


use OpenEMR\Common\Twig\TwigContainer

$path = "/the/path/to/your/templates"; // can be null to default to $GLOBALS['fileroot']/templates
$twigContainer = new TwigContainer($path, $GLOBALS['kernel']);
$twig = $twigContainer->getTwig();

$viewVars = [
    'yourVariable' => 'someValue',
    'var2' => 'anotherValue'
];

echo $twig->render("name_of_your_template.html.twig", $viewVars);

You can set $path to null if you are working on core templates. $kernel is optional, although highly recommended for leveraging debugging. The twig container contains one method, getTwig() which accepts no parameters and returns a Twig\Environment object. Create an array of variables passed to the Twig template, pass that array to the render() along with the name of your template to render the template. You must echo this command.

Debugging

Assuming Kernel was passed to the TwigContainer you can leverage debugging inside of the Twig template. Your environment must be setup for development. The quickest way to do this is:

  1. Copy .env.example to .env (Found in the root directory)
  2. Edit .env and set the variable to dev
  3. Call
    {{ dump() }}
    from your Twig template for functionality similar to print_r()

Filters

Several translation extensions are available within your Twig template. Some of these include:

  • text
  • attr
  • js_escape
  • attr_js
  • attr_url
  • xla
  • xlt
  • xlj
  • xl

See src/Common/Twig/TwigExtension for a complete list of filters.

Use these filters like any other Twig filter: <div>{{ "Text to Translate"|xl</div>

Functions

Several helper functions also exist. Examples include:

  • setupHeader
  • generateFormField
  • tabRow
  • tabData
  • imageWidget

Use these functions like any other Twig function

Global Variables

A few global variables are injected into every Twig render. These variables are highly repetitive and often include file system paths (for use in links). The global variables list should be kept thin as we strive to avoid global bloat. Current global variables are:

  • assets_dir = $GLOBALS[‘assets_static_relative’]
  • srcdir = $GLOBALS[‘srcdir’]
  • rootdir = $GLOBALS[‘rootdir’]
  • webroot = $GLOBALS[‘webroot’]
  • assetVersion = $GLOBALS[‘v_js_includes’]

Access these variables like any other top-level variables in your template.

Note

To better manage the variable space, these global variables may be moved into a global array, so instead of simply calling

{{ webroot }}

you would call

{{ global.webroot }}

.

More Resources

To learn more about Twig please see https://twig.symfony.com/