Hello so I have a simple code here that will render home.html using slim framework and twig. Here's the codes:
In my index.php file:
require_once 'vendor/autoload.php';
$app = new \Slim\Slim([
'debug' => true,
'templates.path' => 'app/views'
]);
$app->view = new \Slim\Views\Twig();
$app->view->setTemplatesDirectory("app/views");
$view = $app->view();
$view->parserOptions = ['debug' => true];
$view->parserExtensions = [new \Slim\Views\TwigExtension()];
$app->get('/home', function () use ($app) {
$app->render('home.html');
});
$app->run();
Here is the base.html template:
And my home.html:
{% extends "base.html" %}
{% block content %}
Some content here
{% endblock %}
My question is, since the only rendered part is the home.html, what if I want some data loaded in my base template? Like this..
So that I won't have to repeat it on every page I render. Is that possible on a base template? Thank you in advance.
Also, this is what I followed to install twig in slim.
I think the best answer is given here. There the answerer say "write a Twig custom function" to load dynamically data in your views.
So you would be able to write your own PHP, can inject your DB and use this along with that templating engine.
Related
I am using twig seperately, not from within Symfony.
I have base layout base.html. Other layouts extend that one and that seems to work fine.
If I have a controlleraction BlogPosts which passes an array of blogposts, I render the blog layout, which extend from the base layout to see that content. That works as intended
Now, I would like to pass variables to the base template, so it is visible on every page. How can I do this?
I found this article, but that mentions it for symfony. On its own, twig does not have the render function.
If you are using twig without symfony, I assume your project directory structure is similar like this:
project
- templates
- base.html.twig
- index.html.twig
- vendor
- index.php
So, your index.php code should be like:
require_once 'vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('templates', getcwd());
$twig = new Twig_Environment($loader);
echo $twig->render('index.html.twig', array('name' => 'Hello'));
So, if you want pass some variable to your base template, twig has method to add value for using globally
require_once 'vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('templates', getcwd());
$twig = new Twig_Environment($loader);
$twig->addGlobal('title', 'HomePage');
echo $twig->render('index.html.twig', array('name' => 'Hello'));
I hope this help
I am trying to work on a project that uses Twig Template. Right now, I am learning it and have checked if I can do any alternate for the project as I know how the MVC architecture works. The Twig Template is different as it has file extension html.twig and the following in it:
{% for user in users %}
<li>{{ user.username | e }}</li>
{% endfor %}
Now for alternate purpose, I've created a controller and view (Not using Twig rules) in the Template as follows that's very basic:
Controller:
public function index()
{
//return something
}
View:
<html>
<head>
<title>Hello World</title>
</head>
<body>
<p>This is a sample page.</p>
</body>
</html>
As you can see, I am not using the default architecture for the project (It works) and thinking not to use Twig architecture for the time being. So my question is if I can continue with raw PHP and basic HTML in the Twig Template architecture? Any idea would be appreciated.
If the view files are being run through Twig, you won't be able to put any PHP statements inside them.
But you can certainly put plain HTML in Twig files, as you've found.
You can use php templating with our without twig
framework:
# ...
templating:
engines: ['twig', 'php']
Render controller in php:
<?php echo $view['actions']->render(
new \Symfony\Component\HttpKernel\Controller\ControllerReference(
'App\Controller\HelloController::fancy',
array(
'name' => $name,
'color' => 'green',
)
)
) ?>
I'm using Laravel basic authentication but I am really struggling to use the Auth object in the views.
There are good examples using Blade, but I am using Twig (twig bridge) and cannot solve this.
I can vardump(Auth::user()->name) in my controller in regular php but how do I get the same in the twig file (my view file)?
How do I do something like;
{% if auth.guest %}
Or;
{{ Auth.user().name }}
I've tried so many different ways but just get nothing.
This has to do with the way twig works, accessing static variables /classes or static methods on classes is impossible without adding a function to the Twig Environment.
You can register a function like so:
$twig = new Twig_Environment($loader);
$twig->addFunction('staticCall', new Twig_Function_Function('staticCall'));
function staticCall($class, $function, $args = array())
{
if (class_exists($class) && method_exists($class, $function))
return call_user_func_array(array($class, $function), $args);
return null;
}
Then i think you should be able to do:
{% if staticCall('Auth', 'guest') %}
Hi there stranger, why don't you login?
{% endif %}
I took the code from this answer: twig template engine, using a static function or variable
I want to set a layout like main.htm for all of my twig files in yii 2, but it loads the folder that controller call first, so I can not call my layout with extends.
in SiteController
public function actionIndex()
{
return $this->render('index.htm');
}
This code calls views/site/index.htm
In my index.htm
{% extends "main.html" %}
So if I put the main.html in site folder, there is no problem, but I want to put it in the layout folder and can be called every controller views .. How can I do that ??
views
->site
->index.html
->layouts
->main.html
For example in symfony we can call like this
{% extends '::base.html.twig' %}
But in Yii2 I can not found a way to do this ....
I have done this with hardcoded the file viewRenderer.php. This is not the way I like it because a composer update the changes are gone away...
Now the function init is like this the loader is null here. I have added loader for my layouts.
$this->twig = new \Twig_Environment(null, array_merge([
'cache' => Yii::getAlias($this->cachePath),
'charset' => Yii::$app->charset,
], $this->options));
After adding a loader ..
$this->loader = new \Twig_Loader_Filesystem($_SERVER["DOCUMENT_ROOT"].'\views\layouts');
And last thing is render function in ViewRenderer.php
public function render($view, $file, $params)
{
$this->twig->addGlobal('this', $view);
//$this->twig->setLoader(new TwigSimpleFileLoader(dirname($file)));
$this->loader->addPath(dirname($file));
return $this->twig->render(pathinfo($file, PATHINFO_BASENAME), $params);
}
I want it without hardcoded changes in the core file of yii2-twig ....
Have you tried using a full path here {% extends "main.html" %}. Something like {% extends "\layouts\main.html" %}
Or even {% extends "#app/views/layouts/main.html" %}
I have not used twig with yii, but it is worth a shot.
I am trying to use template_from_string as stated on
http://twig.sensiolabs.org/doc/functions/template_from_string.html
How can I do that from Silex? I see that the Twig/Exteion/StringLoader.php file is there. Here is the code I've tried
$app['twig'] = $app->share($app->extend('twig', function($twig, $app) {
$twig->addExtension(new MarkdownExtension());
$twig->addExtension(new Twig_Extension_StringLoader());
return $twig;
}));
But when I try to use it like
return $app['twig']->template_from_string(
"The is the {{ title }}",
array('title' => 'Hello')
);
It generates following error
Fatal error: Call to undefined method Twig_Environment::template_from_string()
What I am trying to do is fetch the template content from DB or another file, then render it with Twig instead of using a template file, so I can combine several section templates into the main template. Or if there a better way?
Please note that I already know how to use insert within the template file like
{% include 'home-section.html.twig' %}
but this won't solve my problem because it can not fetch the content data to be parsed automatically.
Thank you.
Just had to create another twig object
$loader = new Twig_Loader_String();
$twig = new Twig_Environment($loader);
echo $twig->render('Hello {{ name }}!', array('name' => 'Fabien'));