Pass Variable to template

madcoda9000
Member | 3
+
0
-

Hello,

I'm new to this and have a problem passing a global variable to all templates.

in my index.php I've the following:

/**
 * init translation util
 */
TranslationUtil::init();
$app->set('trans', fn($key) => TranslationUtil::t($key));

/**
 * configure latte template engine
 */
$app->register('latte', LatteEngine::class, [], function (LatteEngine $latte) use ($app) {
    // translation variable intitialization
    $latte->addProvider('trans', fn() => $app->get('trans'));

    // Setze den Cache-Ordner für Latte
    $cacheDir = '../cache/';

    // Prüfen, ob das Cache-Verzeichnis beschreibbar ist
    if (!is_writable($cacheDir)) {
        LogUtil::logAction(LogType::ERROR, 'index', 'latte->cacheCheck', "ERROR: Cache directory '$cacheDir' is not writable.");
        Flight::halt(500, "Cache directory '$cacheDir' is not writable by the web server.");
    }

    $latte->setTempDirectory($cacheDir);
    $latte->setLoader(new \Latte\Loaders\FileLoader($app->get('flight.views.path')));
});

But when i try to use the variable in my template like this:

{$trans('login.username')}

I get the error, that the variable $trans is not defined.

Interesting fact: when i pass the variable like this (directly to the template), it is working.

Flight::latte()->render('login.latte', [
            'title' => 'Login',
            'sessionTimeout' => SessionUtil::getSessionTimeout(),
            'trans' => Flight::get('trans'),
        ]);
        return;

I hope someone can tell how i can make this variable available to aall templates.

Any hint is welcome..
Sascha

Last edited by madcoda9000 (2025-04-25 09:59)

Marek Bartoš
Nette Blogger | 1298
+
0
-

Providers are not directly accessible, they are used within Latte extensions https://latte.nette.org/en/custom-tags#…

madcoda9000
Member | 3
+
0
-

Thanks for your answer. That means I've to create an extension to use an translation variable in an latte template. Pfuhhh, that sounds complicated to me.. :-(

David Grudl
Nette Core | 8258
+
0
-

I think you're looking for addFunction

$latte->addFunction('trans', fn($s) => $app->get('trans')($s));

and usage

{trans('login.username')}
madcoda9000
Member | 3
+
0
-

@DavidGrudl Awesome! That is exactly what i was looking for. Many thanks.

Btw: is there a similiar way to pass a global constant to all templates? For ex. a language variable?