Working with PHP and Mysql code in TWIG - php

I am working with the TWIG framework for php, and would like to know how i would be able to include these php files inside my php code like i normally do.
<?php
session_start();
include("includes/db.php");
include("functions/searchfunctions.php");
include("functions/userSearchSession.php");
?>
The db file establishes the connection through mysqli to the database.

In your comments you mentioned you are using the Slim framework, which has an extension to support Twig templates.
Using the extension however, requires some additional setup though, you must install the extention, called Slim Views, and also the Twig core from within composer. Slim Views does not list Twig as a dependancy.
To get this working:
Use composer to get add both Slim Views And Twig
$ php composer require slim/views
$ php composer require twig/twig:~1.0
Configure your Slim Framework $app to use the new tempting engine.
$view = $app->view();
$view->parserOptions = array(
'debug' => true,
'cache' => dirname(__FILE__) . '/cache'
);
$view->parserExtensions = array(
new \Slim\Views\TwigExtension(),
);
At this point, Slim Framework is now using Twig when rendering pages. You can now do all of your includes and pass the variables to Twig:
<?php
// ./Slim_app.php
require 'vendor/autoload.php';
/*
* foo.php contains the following:
* <?php
* $foo = bar;
*
*/
require 'foo.php';
$app = new \Slim\Slim(array(
'view' => new \Slim\Views\Twig()
));
$view = $app->view();
$view->parserOptions = array(
'debug' => true,
'cache' => dirname(__FILE__) . '/cache'
);
$view->parserExtensions = array(
new \Slim\Views\TwigExtension(),
);
$app->get('/hello', function () use ($app, $foo) {
//twig_template.html.twig exists in the templates directory.
//(./templates/twig_template.html.twig)
$app->render('twig_template.html.twig', array('foo' => $foo));
});
$app->run();
?>
{# ./templates/twig_template.html.twig #}
{{ foo }}
Navigating to Slim_app.php/hello now displays the following:
More info on using Twig.

Related

how to add twig-view in slimframework v4

I'm trying to add twig-view in slim v4
In slim v3, we add twig-view in container
$container['view'] = function ($c) {
$view = new \Slim\Views\Twig('path/to/templates', [
'cache' => 'path/to/cache'
]);
// Instantiate and add Slim specific extension
$router = $c->get('router');
$uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
$view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
return $view;
};
but I can't add twig like that in slim v4
Update: Twig-View has reached a stable version and the docs are updated to address Slim 4 integration.
If you are still using an unstable version of Twig-View, please consider upgrading.
First, you need to add Twig-View package to your project:
composer require slim/twig-view
And assuming the following directory structure:
composer.json
cache/
public/
|--index.php
templates/
|--hello.twig
vendor/
|--autoload.php
The followings are two working examples:
If you use a container (which is optional according to Slim 4 docs), you can add Tiwg creation definition to the container and use it when required. (I'm using php-di/php-di in this example, but you can use any PSR compatible dependency container.)
index.php, using a container:
<?php
use DI\Container;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
require __DIR__ . '/../vendor/autoload.php';
// Create Container
$container = new Container();
AppFactory::setContainer($container);
// Set view in Container
$container->set('view', function() {
return Twig::create(__DIR__ . '/../templates',
['cache' => __DIR__ . '/../cache']);
});
// Create App
$app = AppFactory::create();
// Add Twig-View Middleware
$app->add(TwigMiddleware::createFromContainer($app));
// Example route
$app->get('/hello/{name}', function ($request, $response, $args) {
return $this->get('view')->render($response, 'hello.twig', [
'name' => $args['name']
]);
});
// Run the app
$app->run();
You can also skip the container creation, but in that case you need to create the Twig instance before trying to render a template.
index.php, without a container:
<?php
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
require __DIR__ . '/../vendor/autoload.php';
// Create App
$app = AppFactory::create();
// Create Twig
$twig = Twig::create(__DIR__ . '/../templates',
['cache' => __DIR__ . '/../cache']);
// Add Twig-View Middleware
$app->add(TwigMiddleware::create($app, $twig));
// Example route
// Please note how $view is created from the request
$app->get('/hello/{name}', function ($request, $response, $args) {
$view = Twig::fromRequest($request);
return $view->render($response, 'hello.twig', [
'name' => $args['name']
]);
});
// Run the app
$app->run();
hello.twig:
Hello {{ name }}
Now try visiting /hello/slim4 in your browser and the output will be:
Hello slim4
SlimTwigView is at 3.0.0 beta (at least as of October 12, 2019), and some things have changed. The few online tutorials I've seen, as well as the official documentation no longer work.
TwigMiddleware no longer takes an instance of the $container as an argument, so you must first put Twig on the Container manually such as:
$container->set('view', function() {
// Of course put correct path to your views here
return new Twig('../views', ['cache' => false]);
});
You then you can add TwigMiddleware to your Slim App using the class' new createFromContainer method, like so:
$app->add(TwigMiddleware::createFromContainer($app));
// which is equivalent to:
// $app->add(TwigMiddleware::createFromContainer($app, 'view'));
At that point, you can render a Twig view like so:
$app->get('/', function (Request $request, Response $response, $args) {
return $this->get('view')->render($response, 'home.twig');
});
When using the Slim specific middleware, you now have access to the additional Twig extensions:
url_for
full_url_for
is_current_url
current_url
get_uri
Well! In my case I was using Slim 4.0 and Twig ^2.5. All I added to my code was
$container->set('view', function () use ($container) {
$view = new \Slim\Views\Twig(
__DIR__ .'/Templates'
, [ 'cache' => false ] //you can turn on caching by providing string path to cache or set to false
);
return $view;
});

render template that is in the views directory but inside another directory

I'm having a hard time trying to make this little modification...
I want to render a file (login.twig) which is inside my views file but in another folder: /views/ajax_files/login.twig
do I have to do this everytime ?
require 'vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('views/ajax_files');
$twig = new Twig_Environment($loader, array(
'cache' => 'cache',
'auto_reload' => true,
));
echo $twig->render('login.twig');
Because on my index.php, that is already being declared
which I'm trying to write DRY code
require 'vendor/autoload.php';
$loader = new Twig_Loader_Filesystem('views');
$twig = new Twig_Environment($loader, array(
'cache' => 'cache',
'auto_reload' => true,
));
echo $twig->render('index.twig');
You can also define multiple template directories directly in your index.php with
$loader = new Twig_Loader_Filesystem(array($templateDir1, $templateDir2));
Please also have a look at http://twig.sensiolabs.org/doc/api.html#loaders, you could also use a loader chain or simply add the additional path to your existent filesystem loader, with some code like
$loader = $twig->getLoader();
$loader->addPath('another/path/to/templates'); //or $loader->prependPath('...')
$twig->setLoader($loader);

HTML is not rendered [Twig] / [Slim]

I am using twig as templating engine but my html is not rendering. All is displayed with the HTML tags itself.
Data from Database can be found by clicking here
I searched SO and got many posts that provides solution but none worked for me
below are the solutions:
Use below code [not working]
{{ detailArticle.artdesc|raw }}
or
{% autoescape false %}
{{ detailArticle.artdesc }}
{% endautoescape %}
Use filter and autoload like below [not working]
$app->view = new \Slim\Views\Twig();
$app->view->setTemplatesDirectory("application/view");
$app->view->parserOptions = array(
'debug' => 'true',
'auto_reload' => true,
'autoescape' => true
);
$app->view->parserExtensions = array(new \Slim\Views\TwigExtension());
Clear Twig cache [I do not have CLI on cPanel, so not sure how to do this]
rm -rf app/cache/* OR rm -rf app/cache/prod/twig OR app/console cache:clear --env=prod
None of the solutions working for me. Please guide.
Data is displayed in same way you will see on the link mentioned above.
My composer.json is as below
{
"name":"panique/mini2",
"homepage":"https://github.com/panique/mini2",
"license":"MIT",
"require":{
"php":">=5.3.0",
"slim/slim": "~2.6",
"slim/views": "~0.1",
"twig/twig": "~1.16",
"panique/pdo-debug": "0.2",
"panique/php-sass": "~1.0",
"matthiasmullie/minify": "~1.3"
},
"autoload":{
"psr-4":{
"Mini\\": "Mini"
}
}
}
I solved this same problem a few months ago.
You need write this in your php:
$escaper = new Twig_Extension_Escaper(false);
$app->view->addExtension($escaper);
My code
require_once 'path_to_Twig/Autoloader.php';
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('path_to_views/');
$twig = new Twig_Environment($loader, array());
$escaper = new Twig_Extension_Escaper(false);
$twig->addExtension($escaper);
echo $twig->render($view_name, $data_to_view);
Steps with your code
Download: http://pear.twig-project.org/get/Twig-1.24.0.tgz
Uncompress and place in you proyect.
Write this in your file:
require 'vendor/autoload.php';
// Initialize Slim (the router/micro framework used)
$app = new \Slim\Slim(array(
'mode' => 'production'
));
require_once 'path_to_Twig/Autoloader.php'; //Substitute the Twig path, the path to the uncompress files in the project
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem('path_to_views/'); //Substitute with the path with the html files
$twig = new Twig_Environment($loader, array());
$escaper = new Twig_Extension_Escaper(false);
$twig->addExtension($escaper);
echo $twig->render($view_name, $data_to_view); //First the name of the view html file, data that you want pass to the view in one array
You need put all this whe you want render the view in the controller, that is to say, you substitute your code by this.
Ran into the same issue and resolved it by adding the Twig_Extnesion_Escaper:
$v = new \Slim\Views\Twig(__DIR__ . '/../../templates', [
'cache' => __DIR__ . '/../../templates/twigcache'
]);
$v->addExtension(new Twig_Extension_Escaper());

How to render a string with variables rather than a template file in Zend Framework 2

I can easily render a template with variables from a file with some code like:
$renderer = new PhpRenderer();
$vm = new ViewModel();
$resolver = new TemplateMapResolver();
$resolver->setMap($this->templateMap);
$renderer->setResolver($resolver);
// Set the template to use and pass in variables as you normally would a view
$vm->setTemplate($template);
if ($vars) {
$vm->setVariables($vars);
}
$content = $renderer->render($vm);
I am curious how I can provide a string to setTemplate rather than a path to a template file. This way, the content being passed in can come from various sources such as an administrator's panel or database.
In the configuration example in the documentation you can see that it is possible to define a template_map inside your view_manager config array. A template map is like an array of aliases for your template files. So inside your module.config.php:
'view_manager' => array(
//...
'template_map' => array(
'name_from_admin_panel' => __DIR__ . '/../view/layout/view.phtml',
'name_from_database' => __DIR__ . '/../view/layout/view.phtml',
)
//...
)
Now you can use these names from your template map to set the template in your ViewModel as normally:
$template = 'name_from_admin_panel';
$viewModel->setTemplate($template);

CodeIgniter How to access session variables in twig templates

somebody can help me please. I'm new in CodeIgniter and Twig. I have declared in my controller the following:
$datasession = array(
'nick' => $sess_nick,
'login_ok' => true
);
$this->session->set_userdata($datasession);
redirect('app'); //app is a controller that render the template view.
then, the question is: How can I get those variables from the twig template? I tried using:
{{ session.userdata.nick }}
but it shows like empty string.
thanks by advance.
To add the session variable on your twig template, you have to add the following line in your Twig library or controller.
$datasession = array(
'nick' => $sess_nick,
'login_ok' => true
);
$this->session->set_userdata($datasession);
$this->_twig->addGlobal("session", $this->CI->session);
Then on your twig template, you can print the session like this
{{ session.userdata.nick }}
Since in CodeIgniter, the session stored by user is usually in the userdata array. Otherwise, you can just simply call the session variable and name
{{ session.nick }}
Src: http://llanalewis.blogspot.co.uk/2013/08/codeigniter-add-session-in-twig.html
Ok, thanks to Latheesan Kanes for your help. It was so much helpful your guideness. I want to share the way I solved this problem.
As Latheesan mentioned we have to use the addGlobal() method (I added this method in my Twig library folder)
like following:
$this->_twig->addGlobal("session", $this->CI->session);
But don't forget before to load the Session library. This way.
$this->CI->load->library('session');
This way you can have your session globally in all your twig views.
I'm using CodeIgniter 3RC3 and the Twig-Codeigniter library (thanks Erik & Bennet!).
To enable easy session access in twig, I added one line to the /application/libraries/Twig.php file's __construct() method:
public function __construct()
{
$this->_ci = & get_instance();
$this->_ci->config->load(self::TWIG_CONFIG_FILE); // load config file
// set include path for twig
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . APPPATH . 'third_party/Twig/lib/Twig');
require_once (string)'Autoloader.php';
// register autoloader
Twig_Autoloader::register();
log_message('debug', 'twig autoloader loaded');
// init paths
$this->template_dir = $this->_ci->config->item('template_dir');
$this->cache_dir = $this->_ci->config->item('cache_dir');
// load environment
$loader = new Twig_Loader_Filesystem($this->template_dir, $this->cache_dir);
$this->_twig_env = new Twig_Environment($loader, array(
'cache' => $this->cache_dir,
'auto_reload' => TRUE));
// ADD SESSION TO TWIG - JZ
$this->_twig_env->addGlobal('session', $this->_ci->session);
// SESSION IS NOW AVAILABLE IN TWIG TEMPLATES!
$this->ci_function_init();
}
Now that we have our session loaded into our twig instance, we access session variables (such as CI's userdata) in our twig templates like so:
<span>__ci_last_regenerate: {{ session.userdata.__ci_last_regenerate }}</span>
phptwigcodeigniter
I successfully used session variables in Twig with this code:
In controller:
$datasession = array(
'language' => "PHP",
'framework' => "CodeIgniter"
);
$this->session->set_userdata($datasession);
$this->twig->addGlobal("session", $this->session);
In template:
{{ session.language }}
{{ session.framework }}
I'm using https://github.com/kenjis/codeigniter-ss-twig

Categories