Sending variables to Symfony template file - php

I'm trying to send a variable to a twig file which is not in the typical location, Usually I'm loading views by specifying their path through the Bundle but the file I want to send a variable to is not, hierarchically, on the same level as the other twig templates.
I've a controller which looks like the following:
public function fooAction(Request $request)
{
*//Query*
return $this->render('Bundle:file.html.twig', array('varToSend' => $queryResult));
}
I'm pretty sure the Bundle:file.html.twig is wrong but I don't know how else to specify the relevant path in twig.

Twig you would get from container would not work with arbitrary paths, but you can initialize your own twig:
$twig = new \Twig_Environment(new \Twig_Loader_String());
$rendered = $twig->render(
file_get_contents('/path/to/your/file.html.twig'),
array('varToSend' => $queryResult)
);
If you need this in more than one place, consider making it a Symfony service in order to not initialize Twig Environment every time.
Note that renderer in this case won't have any of Symfony's Twig Extensions, you'll have to add them manually.
If possible, try to avoid this, and put templates into app/Resources/views or src/AppBundle/Resources/views directories.

You have to use a path like that :
return $this->render('Bundle:Something:file.html.twig', array(
'varToSend' => $queryResult
));
And put your file in this folder :
src/Bundle/Resources/views/Something/file.html.twig

Related

Dynamically resolvable Twig namespaces

I have a Symfony application that handles request from multiple domains. On these domains, customers have the ability to create custom Twig templates that can be used in their CMS module. These templates are saved to a /path/to/ftp/example.com/cms_templates/ directory.
In previous versions of Symfony, rendering these templates was not an issue. On an incoming request on mydomain.com/page_one, the absolute path of the Twig template could be resolved to e.g. /path/to/ftp/mydomain.com/cms_templates/page_one.html.twig. The existence of the template was verified and the template was rendered. However, in Symfony 4 support for absolute template paths has been removed.
I thought of registering an extra Twig namespace in twig.paths called 'custom' that points to /path/to/ftp and then reference the templates with #custom/mydomain.com/cms_templates/page_one.html.twig. The problem is, /path/to/ftp contains not only templates but loads and loads of other files too. And the TemplateCacheWarmer is looping through all of these files.
What I'am actually looking for is a way to register a Twig namespace, say #cms that is resolved on the fly such that I can inject the hostname of the current request in it. I would then be able to reference a template using #cms\page_one.html.twig. Cache warmup isn't necessary for these templates.
How to achieve such functionality? I looked ad the Twig documentation but it looks like I just can't figure it out.
TLDR; How to get Symfony/Twig to resolve the template #foo\template.html.twig to /path/to/domain.com/templates/template.html.twig when domain.com differs between requests.
One solution would be to prepend configuration
public function prepend(ContainerBuilder $container)
{
$bundles = $container->getParameter('kernel.bundles');
if (isset($bundles['TwigBundle'])) {
$config = $container->getExtensionConfig('twig')[0];
$paths = ['/path/to/cms' => 'cms'];
if (array_key_exists('path', $config)) {
$paths = array_merge($config['paths'], $paths);
}
$config['paths'] = $paths;
$container->prependExtensionConfig('twig', $config);
}
}
The problem would be this:
If you are building some kind of CMS - then this would mean - no other bundle/module/plugin could ever register additional twig namespaces again - if I am right.
So... I am interested in other solutions if there are some.

Dealing with Views in Phalcon Controllers

I am working on a newly created Phalcon project, and I don't really know how to actually use multiples views.
What is the entry point? I don't really know when each method in the controller is called, under which conditions, etc.
Where is the control flow defined? is it based in the name of the view? or is there a place where you can register them?
Phalcon is a bit different than other well-known PHP frameworks, in that not much is pre-configured or pre-built by default. It's quite loosely-coupled. So you have to decide where and how your control flow will work. This means that you will need to dig deeper in the documentation and also that there could be different way to achieve the same thing.
I'm going to walk you through a simple example and provide references, so you can understand it more.
1) You would start by defining a bootstrap file (or files) that will define the routes, or entry points, and will setup and create the application. This bootstrap file could be called by an index.php file that is the default file served by the web server. Here is an example of how such bootstrap file will define the routes or entry points (note: these are just fragments and do not represent all the things that a bootstrap file should do):
use Phalcon\Di\FactoryDefault;
// initializes the dependency injector of Phalcon framework
$injector = new FactoryDefault();
// defines the routes
$injector->setShared('router', function () {
return require_once('some/path/routes.php');
});
Then it the routes.php file:
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Group as RouterGroup;
// instantiates the router
$router = new Router(false);
// defines routes for the 'users' controller
$user_routes = new RouterGroup(['controller' => 'users']);
$user_routes->setPrefix('/users');
$user_routes->addGet('/show/{id:[0-9]{1,9}}', ['action' => 'show']);
$router->mount($user_routes);
return $router;
Im defining routes in an alternate way, by defining routes groups. I find it to be more easy to organize routes by resource or controller.
2) When you enter the url example.com/users/show/123, the routes above will match this to the controller users and action show. This is specified by the chunks of code ['controller' => 'users'], setPrefix('/users') and '/show/{id:[0-9]{1,9}}', ['action' => 'show']
3) So now you create the controller. You create a file in, let's say, controllers/UsersController.php. And then you create its action; note the name that you used in the route (show) and the suffix of Action:
public function showAction(int $id) {
// ... do all you need to do...
// fetch data
$user = UserModel::findFirst(blah blah);
// pass data to view
$this->view->setVar('user', $user);
// Phalcon automatically calls the view; from the manual:
/*
Phalcon automatically passes the execution to the view component as soon as a particular
controller has completed its cycle. The view component will look in the views folder for
a folder named as the same name of the last controller executed and then for a file named
as the last action executed.
*/
// but in case you would need to specify a different one
$this->view->render('users', 'another_view');
}
There is much more stuff related to views; consult the manual.
Note that you will need to register such controller in the bootstrap file like (Im also including examples on how to register other things):
use Phalcon\Loader;
// registers namespaces and other classes
$loader = new Loader();
$loader->registerNamespaces([
'MyNameSpace\Controllers' => 'path/controllers/',
'MyNameSpace\Models' => 'path/models/',
'MyNameSpace\Views' => 'path/views/'
]);
$loader->register();
4) You will also need to register a few things for the views. In the bootstrap file
use Phalcon\Mvc\View;
$injector->setShared('view', function () {
$view = new View();
$view->setViewsDir('path/views/');
return $view;
});
And this, together with other things you will need to do, particularly in the bootstrap process, will get you started in sending requests to the controller and action/view defined in the routes.
Those were basic examples. There is much more that you will need to learn, because I only gave you a few pieces to get you started. So here are some links that can explain more. Remember, there are several different ways to achieve the same thing in Phalcon.
Bootstrapping:
https://docs.phalconphp.com/en/3.2/di
https://docs.phalconphp.com/en/3.2/loader
https://docs.phalconphp.com/en/3.2/dispatcher
Routing: https://docs.phalconphp.com/en/3.2/routing
Controllers: https://docs.phalconphp.com/en/3.2/controllers
More on Views (from registering to passing data to them, to templating and more): https://docs.phalconphp.com/en/3.2/views
And a simple tutorial to teach you some basic things: https://docs.phalconphp.com/en/3.2/tutorial-rest
The application begins with the routing stage. From there you grab the controller and action from the router, and feed it to the dispatcher. You set the view then call the execute the dispatcher so it access your controller's action. From there you create a new response object and set its contents equal to the view requests, and finally send the response to the client's browser -- both the content and the headers. It's a good idea to do this through Phalcon rather than echoing directly or using PHP's header(), so it's only done at the moment you call $response->send(); This is best practice because it allows you to create tests, such as in phpunit, so you can test for the existence of headers, or content, while moving off to the next response and header without actually sending anything so you can test stuff. Same idea with exit; in code, is best to avoid so you can write tests and move on to the next test without your tests aborting on the first test due to the existence of exit.
As far as how the Phalcon application works, and in what steps, it's much easier to follow the flow by looking at manual bootstrapping:
https://docs.phalconphp.com/en/3.2/application#manual-bootstrapping
At the heart of Phalcon is the DI, the Dependency Injection container. This allows you to create services, and store them on the DI so services can access each other. You can create your own services and store them under your own name on the DI, there's nothing special about the names used. However depending on the areas of Phalcon you used, certain services on the DI are assumed like "db" for interacting with your database. Note services can be set as either shared or not shared on the DI. Shared means it implements singleton and keeps the object alive for all calls afterwards. If you use getShared, it does a similar thing even if it wasn't initially a shared service. The getShared method is considered bad practice and the Phalcon team is talking about removing the method in future Phalcon versions. Please rely on setShared instead.
Regarding multiple views, you can start with $this->view->disable(); from within the controller. This allows you to disable a view so you don't get any content generated to begin with from within a controller so you can follow how views work from within controllers.
Phalcon assumes every controller has a matching view under /someController/someView followed by whatever extension you registered on the view, which defaults to .volt but can also be set to use .phtml or .php.
These two correspond to:
Phalcon\Mvc\View\Engine\Php and Phalcon\Mvc\View\Engine\Volt
Note that you DON'T specify the extension when looking for a template to render, Phalcon adds this for you
Phalcon also uses a root view template index.volt, if it exists, for all interactions with the view so you can use things like the same doctype for all responses, making your life easier.
Phalcon also offers you partials, so from within a view you can render a partial like breadcrumbs, or a header or footer which you'd otherwise be copy-pasting into each template. This allows you to manage all pages from the same template so you're not repeating yourself.
As far as which view class you use within Phalcon, there's two main choices:
Phalcon\Mvc\View and Phalcon\Mvc\View\Simple
While similar, Phalcon\Mvc\View gives you a multiple level hierarchy as described before with a main template, and a controller-action based template as well as some other fancy features. As far as Phalcon\Mvc\View\Simple, it's much more lightweight and is a single level.
You should be familiar with hierarchical rendering:
https://docs.phalconphp.com/en/3.2/views#hierarchical-rendering
The idea is with Phalcon\Mvc\View that you have a Main Layout (if this template exists) usually stored in /views/index.volt, which is used on every page so you can toss in your doctypes, the title (which you would set with a variable the view passed in), etc. You'd have a Controller Layout, which would be stored under /views/layouts.myController.volt and used for every action within a controller (if this template exists), finally you'd have the Action Layout which is used for the specific action of the controller in /views/myController/myAction.volt.
There are all types of ways you can break from Phalcon's default behavior. You can do the earlier stated $this->view->disable(); so you can do everything manually yourself so Phalcon doesn't assume anything about the view template. You can also use ->pick to pick which template to use if it's going to be different than the controller and action it's ran in.
You can also return a response object from within a controller and Phalcon will not try to render the templates and use the response object instead.
For example you might want to do:
return $this->response->redirect('index/index');
This would redirect the user's browser to said page. You could also do a forward instead which would be used internally within Phalcon to access a different controller and/or action.
You can config the directory the views are stored with setViewsDir. You can also do this from within the controller itself, or even within the view as late as you want, if you have some exceptions due to a goofy directory structure.
You can do things like use $this->view->setTemplateBefore('common') or $this->view->setTemplateAfter('common'); so you can have intermediate templates.
At the heart of the view hierarchy is <?php echo $this->getContent(); ?> or {{ content() }} if you're using Volt. Even if you're using Volt, it gets parsed by Phalcon and generates the PHP version with $this->getContent(), storing it in your /cache/ directory, before it is executed.
The idea with "template before" is that it's optional if you need another layer of hierarchy between your main template and your controller template. Same idea with "template after" etc. I would advise against using template before and after as they are confusing and partials are better suited for the task.
It all depends on how you want to organize your application structure.
Note you can also swap between your main template to another main template if you need to swap anything major. You could also just toss in an "if" statement into your main template to decide what to do based on some condition, etc.
With all that said, you should be able to read the documentation and make better sense of how to utilize it:
https://docs.phalconphp.com/en/3.2/api/Phalcon_Mvc_View

Parsing Laravel Config in PHP

Laravel has config files of which are great for storing variables that are accessed from every page on my website. The current app.php config file contains:
return [
'name' => 'This is a name',
'slogan' => 'This is a slogan!',
'primary_color' => '#cc0202',
'secondary_color' => '#990000',
'tertiary_color' => '#FFFFFF'
];
This is just an associative array that of which can be accessed by Blade code using:
{{ config('app.primary_color', '#cc0202') }}
However I wish to use the data from within a .php file that is in the public folder. Files that are in the public folder can not use Blade. What would be the best way to get this data?
If you want to use your Laravel's config in PHP files in public directory just require this file by
$config = include '../config/app.php'; // Go back to main catalog
// and go to config catalog
and use it as normal array.
For example
echo $config['primary_color'];
But in my opinion is very bad practice to put PHP files in public catalog if you are using a framework.
Try this
<?php $variable = config('app.primary_color', '#cc0202') ?>
To access and print:
echo config('app.primary_color');
To set data:
config(['app.primary_color' => '#cc0202']);
Why don't you use a custom service provider instead ?
From laravel documentation:
Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services are bootstrapped via service providers.
https://laravel.com/docs/5.3/providers , You can see this helpful tutorial on laracasts to: https://laracasts.com/series/laravel-5-fundamentals/episodes/25

Extend blade engine in Laravel to use different views directory

I am working on a Laravel project and I am very new to it. For now, I want to use blade templates to render views but I want it to search for views in different directories like <custom_dir>\views instead of default resources/views.
The <custom_dir> will be dynamic (it can be a variable).
Any ideas? I was thinking of a custom service provider and then extend the default function which renders views in Laravel inside it. But not sure how to implement it.
Edit:
I have user this link to extend the default functionality of include function in blade template engine. But this overrides the include functionality. I want to change the path and then call the default blade functionality
You could probably append the path to the configuration:
1) Statically, by modifying file config/view.php
'paths' => [
realpath(base_path('resources/views')),
//more paths here
],
2) Dynamically at runtime:
$paths = config('view.paths');
$paths[] = $newPathToAdd;
config(["view.paths" => $paths ]);
I suggest you use this in moderation otherwise you will just end up with a mess of directories with no real specified purpose.
You can create custom directories in resources\views directory and use them with something like this:
return view($customDirectory.'.index');
Where index is a template inside custom directory.

How to render two different view models in the same action with Zend\Cache\Pattern\CaptureCache

With any regular page I set up a Zend\Cache\Pattern\CaptureCache, catch the onFinish event, and send the rendered version to a message queue for later processing. So far, so good...
Problem: sometimes I need to render two versions of the same action in the same request; one for mobile and one for desktop and I'm not sure how to do that.
If it helps, the actions that I need to "double render" actually create two discrete ViewModel objects so that I can have full control over that.
Ended up creating a service that given these two view models would figure out which one is mobile and which one is desktop. Then it would grab the layout and render each view model separately. Finally it would bypass any caching and generate both files manually.
With the setTemplate method :)
First you create your phtml view file (already done I suppose).
then you declare it in your view manager config / template_map :
In the Module.config.php file (you create the alias to call it later in your controller) :
return array(
//[...],
'view_manager' => array(
'template_map' => array(
// [...],
'index/test' => __DIR__ . '/../view/mymodule/index/test.phtml',
),
//here your template_path_stack as usual
),
// [...],
);
(of course, put your own path ;) )
Then in your controller :
public function indexAction(){
$view = new ViewModel();
if (/*here your tests*/) {
$view->setTemplate('index/test'); //here the name declared in the template_map
}
return $view;
}
you can learn a lot here about views (and layouts): http://framework.zend.com/manual/2.2/en/modules/zend.view.quick-start.html

Categories