Path of CSS files in Symfony2 for Twig rendering - css

Problem
I need to generate CSS file while page is rendering (custom colors for each user). In order to achieve that I made an action to render the file and and put the route as a reference, like that:
public function styleAction()
{
$backgroundColor = $this->getUser()->getCompany()->getBackgroundColor();
if(!$backgroundColor || $backgroundColor =="")
$backgroundColor = '#b5dea2';
$response = new Response();
$response->setContent($this->render('*WHAT_TO_PUT_HERE*:style.css.twig',array('backgroundColor' => $backgroundColor)));
$response->headers->set('Content-Type', 'text/css');
return $response;
}
Route:
css_route:
path: /css/mainStyle
defaults: { _controller: AcmeMainBundle:Default:style }
Question:
What to write in place of "WHAT_TO_PUT_HERE" in order to access to the file located under /web/css/style.css.twig.

Put the file in your Bundles Resources\views directory.

Related

Best way to change routes loading order

I have routes in my controller loaded in /config/routes/annotations.yaml
controllers:
resource: ../../src/Controller/
type: annotation
I have routes in /config/routes.yaml
about:
path: /about
controller: Symfony\Bundle\FrameworkBundle\Controller\TemplateController::templateAction
defaults:
template: front/about.html.twig
...
Dynamic routes in "controllers" are overriding my "static" routes.
What is the best way to load "static" routes before those in controllers.
I made it work by commenting the content in /config/routes/annotations.yaml and pasting it in the end of /config/routes.yaml but I don't feel it's the best way to do it...
Technically this might not be enough though. Any route loaded after this will be ignored, and if you are using annotations, you have to put this action in the last action of the last controller sorted alphabetically.
Configure this route in yml, and put it at the end of routes.yml.
This route will be the last to execute (performance hit), and it will catch all requests, so make sure you throw 404-s properly.
(Am I right in assuming that the client wants to be able to configure routes completely? eg CMS pages? Had that situation a couple of times)
It didn't want to change my url nor using the alphabetical trick as suggested in the comments.
I fixed it by changing the order of imported routes in the kernel.
Instead of:
protected function configureRoutes(RouteCollectionBuilder $routes)
{
$confDir = $this->getProjectDir().'/config';
$routes->import($confDir.'/{routes}/*'.self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob');
}
I
protected function configureRoutes(RouteCollectionBuilder $routes)
{
$confDir = $this->getProjectDir().'/config';
# routes loaded in routes.yaml
$routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob');
# routes loaded in routes/annotations.yaml
$routes->import($confDir.'/{routes}/*'.self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, '/', 'glob');
}
You can avoid changing the kernel logic by putting the controller with annotations after the static route in routes.xml:
browserconfig:
path: /browserconfig.xml
controller: Symfony\Bundle\FrameworkBundle\Controller\TemplateController::templateAction
defaults:
template: browserconfig.xml.twig
app_document:
resource: App\Controller\DocumentController
type: annotation

How to Hide parameters in URL in Symfony2

I don't want the user see the parameters in my URL.
Example :
my_route:
path: /***/{id}
defaults: { _controller: MyBundle:Default:myaction}
the route will be generated like this :
***/product/1
i want just see the
***/product
As explained in comments, the request needs something to identify the resource you want to fetch. But this has nothing to do with URL rewriting. If you want to display the slug of the resource instead of the id, do the following :
my_route:
path: /products/{slug}
defaults: { _controller: MyBundle:Default:myaction}
Then, in MyBundle/Controller/DefaultController.php :
public function myactionAction(Request $request, $slug)
{
$product = $this->getDoctrine()->getManager()->getRepository('MyBundle:Product')->findOneBy(["slug" => $slug]);
}
and when you want to create a link to this product, use
link to the product

symfony2 : apply different template with special parameter?

How can I apply different template (view) when I type ?t=1 in the url ?
Examples :
mysite.com -> opens home with default template, let's say home.twig
mysite.com/?t=1 -> opens home with another template : home1.twig (or 1/home.twig)
Is it possible ?
Thanks :)
Sure, you can define different routes for this, but second url should look like "mysite.com/1":
route_1:
pattern: /
defaults: { _controller: AppBundle:Index:home }
route_2:
pattern: /{t}
defaults: { _controller: AppBundle:Index:custom }
requirements:
t: '[0-9]+'
A second approach is to load different views based by existence of "t" parameter:
public function homeAction(Request $request)
{
$view = $request->query->has('t') && $request->query->get('t') == 1 ? 'home1.twig.html' : 'home.twig.html';
return $this->render($view, $params);
}

How to use YUI compressor in Symfony2 routing/controller

How can I use the YUI compressor with following scenario:
routing.yml
js_route:
pattern: /foo/bar.{_format}
defaults: { _controller: FooBundle:Default:JS }
requirements:
_format: js
DefaultController.php
public function JSAction() {
// ...
// content for JS file is being generated
// ...
return $this->render('FooBundle:Default:bar.js.twig', $returnarray);
// ...
}
I know how to use it in my twig templates (e.g. {% javascripts '#FooBundle/Resources/public/js/*' filter='?yui_js' %}) but unfortunately not for above.
Any hints? Thanks!
I don't actually suggest you do this because the YUI JS compressor will be loaded on every request to the resource. But this is one way to do it anyway.
Note, in order to keep the example simple I've excluded any extra code to properly determine your web root and location of the jar file.
$path = $this->container->getParameter('kernel.root_dir');
$ac = new \Assetic\Asset\AssetCollection(array(
new \Assetic\Asset\FileAsset($path . '/../src/WebBundle/Resources/public/js/jquery.longclick.js')
), array(
new \Assetic\Filter\Yui\JsCompressorFilter($path . '/Resources/java/yuicompressor-2.4.7.jar')
));
$compressJS = $ac->dump();
return new Response($compressJS, 200, array('Content-Type' => 'text/javascript'));
Also note, you're not just limited to FileAsset(). There are other classes available like StringAsset(), etc, so you can build content dynamically.

Get routing requirement variable in Symfony2

in order to create a navigation for me webinterface I'd like to get a variable from the routing config of my bundle. I define the available pages in mybundle/Resources/config/routing.yml.
mybundle_homepage:
pattern: /{_locale}/{branch}/{page}
defaults: { _controller: mybundle:mycontroller:index, _locale: de, branch: x.x.x, page: start }
requirements:
_locale: de|en
page: start|functions|events|constants|styleguide
Now I had a look at the Symfony2 YAML Parser and I have to provide a filepath to it's static method parse: http://symfony.com/doc/2.0/reference/YAML.html
mycontroller.php
use Symfony\Component\Yaml\Yaml;
class mycontroller extends Controller
{
public function indexAction($_locale, $branch, $page)
{
$routing = Yaml::parse('../Resources/config/routing.yml');
var_dump($routing);
}
}
I thought I could do it that way because the folder hirarchy looks like that:
mybundle
Controller
mycontroller.php
Rescources
config
routing.yml
But it's not working. Any ideas or maybe another way to get the requirements.page array from the routing file?
Regards, Ben
You should be able to access the router service inside a class that's DI container aware. So, you can write something like:
$routes = $this->container->get('router')->getRouteCollection();
$route = $routes->get('my_route_name');
print_r($route->getRequirements());

Resources