Symfony2 cannot render template inside Bundle - php

I have the following structure:
/src/Product/AdminBundle/Resources/views/main.twig
I am trying to render this template from controller:
$this->render(...);
or from routing.yml
index_page:
path: /
defaults:
_controller: FrameworkBundle:Template:template
template: ...
How can I render this from from inside the controller in the bundle? Here is what I have tried with no luck:
Product:AdminBundle:main.twig
ProductAdminBundle:main.twig
#ProductAdminBundle:main.twig
#ProductAdminBundle/main.twig
ProductAdminBundle/main.twig
ProductAdminBundle/Resources/views/main.twig
Product/AdminBundle/Resources/views/main.twig
AdminBundle:main.twig
AdminBundle/main.twig

The usual path syntax is:
BundleName:DirectoryInView:file.html.twig
In your case, this will be:
ProductAdminBundle::main.html.twig
We use ::, because your view is located in the root directory.

After trying every possible combination this is the one that worked for me:
#AdminBundle/Resources/views/main.twig

Try like this:
return $this->render('ProductAdminBundle:main.html.twig', []);
Where main.html.twig is your view name (and not main.twig).

AdminBundle::main.twig does not work
rename main.twig into main.html.twig
After that AdminBundle::main.html.twig will work!

Related

How to link twig template in href?

How can I link a twig template? Something like this:
Learn more
Is there a way to do this or do I have to use URL rewriting?
You can use template controller for this. Just add new route, specify template controller FrameworkBundle:Template:template and twig template.
routes.yml
qwerty:
path: /qwerty
defaults:
_controller: FrameworkBundle:Template:template
template: Events.twig
and change this link to:
Learn more
http://symfony.com/doc/current/templating/render_without_controller.html
Your question is conceptually flawed. Twig is a templating language, and cannot be rendered as a web page on its own.
You probably don't want to link directly to a .twig file (in fact, .twig files should not be directly be accessible in your public document root at all)! Rather, you need some PHP code (either a standalone script, or preferably, a front controller route) that renders your template in the context of your application, and returns the fully rendered page at a URL that you have specified.
For example, in the Slim framework, you might do something like:
// Render Twig template in route
$app->get('/events', function ($request, $response, $args) {
return $this->view->render($response, 'events.html.twig');
});
// Run app
$app->run();
See this article for more information on moving away from procedural spaghetti code and thinking in MVC terms.
If you are using twig the template will need to be parsed, so you cannot link in the way you have tried. In Symfony 2 you would use something like {{ path('name_of_path') }}, you will need to name your route first though.
You can name the route with name="event" with Annotations:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
/**
* Matches /event exactly
*
* #Route("/event", name="event")
*/
public function eventAction()
{
// ...
}
In the twig template link with this:
Event
More info here:
http://symfony.com/doc/current/templating.html#linking-to-pages
You can't. Make another controller action that renders Events.twig and link to the respective route using path():
Learn more
https://symfony.com/doc/current/controller.html#a-simple-controller
http://symfony.com/doc/current/routing.html

Is it possible to construct a Symfony path using only parameters?

I would like to reduce the number of repetitive code and give a canonical URL in my Drupal 8 application. Since the routing system is built on Symfony, I included it in the title.
I am constructing paths under routes in my mymodule.routing.yml file. I want to match a specified number of different strings in the first argument, and a slug which can be any string in the second argument. It looks like this:
entity.my_entity.canonical:
path: '/{type}/{slug}'
defaults:
_controller: '\namespace\PostController::show'
requirements:
_permission: 'perm'
type: different|strings|that|can|match|
Now, when I try to access using for example /match/some-slug then it just says "Page not found".
If I something static to the path, for example path: '/j/{type}/{slug}', then it works as expected when I open /j/match/some-slug in the browser.
My boss doesn't like any unnecessary characters in the URL though, so I would like to achieve this by using two parameters, like shown in the first example.
As Yonel mentioned in the comments you can use debug:router to check all your routes. I don't see anything wrong with your code.
Try running bin/console router:match "/match/blaaa" and if you see some controller that isn't the one you want then you'll need to change the route. It shouldn't be the case though because you're getting a 404.
Here's my exact setup that works
routing.yml:
entity.my_entity.canonical:
path: '/{type}/{slug}'
defaults:
_controller: 'MyBundle:Something:foo'
requirements:
type: different|strings|that|can|match|
Inside MyBundle\SomethingController:
public function fooAction($id)
{
return new Response("bar");
}
Then going to http://localhost/match/fom shows the "bar" response.
I have read the documentation again (RTM), and found out that it is not possible in Drupal 8, while it is possible in Symfony.
Note that the first item of the path must not be dynamic.
Source: Structure of routes in Drupal 8

Need Assistance with Symfony 2.7 creating first page

I am trying to learn the Symfony framework and struggling with it. The instructions are not very helpful or assume I know a lot more than I know. I am just trying to create a single web page with proper route and controller. I have been googling to find answers and made some progress but no luck yet. Right now I just have the standard install of Symfony with just default bundles etc. I created a project called "gtest3" and chose PHP for it...
I am not sure where I put the new route in (what file) or maybe it needs to be put in more than one file?
I found the "routing.yml" file which seems that is where I need to put it...
here is what is in there right now:
gtest3:
resource: "#gtest3Bundle/Resources/config/routing.php"
prefix: /
app:
resource: "#AppBundle/Controller/"
type: annotation
I am guessing I need to add something to this and put the location/filename of the controller? I have tried doing this a few ways and just get errors.
There is also the "routing.php" file that is referenced in the above code. I am not sure if this is the "controller" or if it is an additional piece of the "route". Here is the code from that file:
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('gtest3_homepage', new Route('/hello/{name}', array(
'_controller' => 'gtest3Bundle:Default:index',
)));
return $collection;
I am not sure what if anything I would add here.
Finally - there is the "DefaultConroller.php" file I found as well which may also be the controller. I dont think I need to include the code of that file here.
So - all I am trying to do is create a route of maybe "/gman" and then have the controller just echo something on the page. Super basic stuff. And I cannot figure out how to get this going.
Can anyone help with this? Thanks so much...
You can define your routes in three ways, either by using yml files, xml files, or by using a php file. This is documented behaviour.
You are from the looks of your routing.yml trying to set up a php version. I would not recommend it, and instead use configuration over coding the routing.
The annotation example would look like:
Adding a controller:
namespace Gtest3Bundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class Gtest3Bundle extends Controller
{
/**
* #Route("/hello/{name}")
* #Template()
*/
public function indexAction($name)
{
return array('name' => $name);
}
}
And add in your app/config/routing.yml:
gtest3:
resource: "#Gtest3Rights/Controller/"
type: annotation
prefix: /what-ever-you-want
You can check what kind of routes you have defined by using:
./app/console router:debug
If it doesn't appear hear, you have something misconfigured.
Please be advised that your bundle names breaks the convention of how bundles should be named in the symfony2 context.
It is advised to use NamespaceProjectBundle. This also documented. If you are stuck, try generating a bundle via the ./app/console generate:bundle. This way you can create a whole symfony2 structure which should show the default page hello/foo page just fine.
If it doesn't seem to run at all, make sure you have registered your bundle at the in the app/AppKernel.php file in the registerBundles() method.
To configure routes you can use yml, php or xml file. You can specify it in app/config/config.yml
framework:
router:
resource: "%kernel.root_dir%/config/routing.yml"
It's where you can check which file is used now.
There are some manners to store the routes.
app:
resource: "#AppBundle/Controller/"
type: annotation
This is how you use routes by writing annotations above your actions (eg indexAction) inside your controller class. Read more.
Another common approach is to build one or more .yml files inside each Bundle.
in app/config/routing.yml you should write this:
app:
resource: "#AppBundle/Resources/config/routing.yml"
prefix: /
Then you need to create the file (and directories if necessary) src/AppBundle/Resources/config/routing.yml and add the following content:
app_homepage:
path: /
defaults: { _controller: AppBundle:Default:index }
It will then try to find the DefaultController and fires the indexAction in the AppBundle (src/AppBundle/Controller/DefaultController.php).
To debug your routes simply type in your console from your projects directory:
app/console router:debug

Symfony, routing.yml is not working

I have a project in sympfony.
Im trying to add a new page, and i have done usual steps, but nothing seems to work.
I have added the following to src/ITWB/FrontBundle/Resources/config/routing.yml:
itwb_front_abc:
pattern: /abcCenter
defaults: { _controller: ITWBFrontBundle:Footer:abcCenter }
In my src/ITWB/FrontBundle/Controller/FooterController.php i have added this:
public function abcCenterAction() {
return $this->render('ITWBFrontBundle::test.html.twig');
}
But it's not working.
I have tried putting and "echo" inside the action, and it isnt displaying, so, the problem is in the routing, domain.com/abcCenter its not being recognized. I have also tried with other names and it's the same.
What can i do ?
Thanks
You forgot the indent the options. Indenting is a really important aspect of Yaml:
itwb_front_abc:
pattern: /abcCenter
defaults: { _controller: ITWBFrontBundle:Footer:abcCenter }
Take care of indent, like Wouter J says.
You can access abcCenter via domain.com/app_dev.php/abcCenter (not domain.com/abcCenter) if your website is running local, otherwise you have to clear cache:
php app/console cache:clear --env=prod --no-debug
How to deploy a Symfony2 application.
The first place I would look: in app/config/routing.yml, do you have a reference to your bundle's routing.yml?
The app/config/routing.yml file should contain a couple of lines something like this:
front_bundle:
resource: "#FrontBundle/Resources/config/routing.yml"
Of course maybe you've done this already as part of the "usual steps" you mention?

need some help about codeigniter route

Is there a way to make the route in codeigniter work like that in symfony?
Cause in there you can rename the route path and it still wouldn't affect your output cause what you call is the route name not the route path unlike in codeigniter.
For example, in symfony, routes are set like this:
news_index:
path: /news
defaults: { _controller: CmsBundle:News:index }
news_view:
path: /news/view/{id}
defaults: { _controller: CmsBundle:News:view }
and then I can access that in my template by calling the route name, not the route path
<?php
// outputs: /news
echo $view['router']->generate('news_index');
// outputs: /news/view/1
echo $view['router']->generate('news_view',array('id' => $news_id));
?>
so if I change the route path it wouldn't affect the way i call it in my code because i'm calling the route name, all it will do is change the output:
news_index:
path: /articles
defaults: { _controller: CmsBundle:News:index }
news_view:
path: /articles/item/{id}
defaults: { _controller: CmsBundle:News:view }
still same code but output is changed
<?php
// outputs: /articles
echo $view['router']->generate('news_index');
// outputs: /articles/item/1
echo $view['router']->generate('news_view',array('id' => $news_id));
?>
while in codeigniter, if i set my route like this:
$route['news'] = 'NewsController';
$route['news/view/(:num)'] = 'NewsController/view/$1';
the only way i know to call it is by the route path:
<?php
echo anchor('news');
echo anchor('news/view'.$news_id);
?>
and if I change my path, I would have to change what I wrote in view as well. That would be a hassle. So I'm wondering if there could be a way to make it work like in symfony. I would appreciate it if anyone could help me. And I apologize if my explanation is not clear. English is not my mother tongue :)
There is blog post available from #kennyk that describes his approach to symfony-like named routes using a router extension.
The article is called Easy Reverse Routing with CodeIgniter.
I guess that's what you're looking for.

Categories