Am not very familiar with twig, am trying to get an image extention, but am not sure how to do this in twig ,in php it's very easy using string functions such as substr and indexof or with the following: ext=pathinfo('/testdir/dir2/image.gif', PATHINFO_EXTENSION), i don't want to code it in controller and pass it to twig as parameter,instead i want to extract it directly in the twig layout,so how am going to do this?
You can get file extension by this way
{{ "filename.txt"|split('.')|last }}
One approach would be to use Twig's slice filter.
For example, if the path to your image file is imgSrc, then imgSrc|slice(-4) will give you the last 4 characters of the filename (eg. .gif, .jpg, jpeg).
You can create Twig extension, that will contain
namespace YourApp\AcmeBundle\Twig;
class MyTwigExtension extends \Twig_Extension
{
public function getFilters(){
return array(
new \Twig_SimpleFilter('ext', array($this, 'ext')),
);
}
public function ext($filepath){
$ext = pathinfo($filepath, PATHINFO_EXTENSION);
return $ext;
}
}
In twig, use the split filter. see http://twig.sensiolabs.org/doc/filters/split.html
you can also simply get the extension in the controller and pass it to twig.
Related
How can i create the global variable in symfony controller like in laravel (example: view()->share('now', date('Y-m-d')); ), that it availiable in all templates?
Setting a global template variable
It is possible to set a global variable available in every template using the addGlobal function in the BaseController class.
$this->get('twig')->addGlobal('today', date('Y-m-d'));
The Twig date functions
Remember that Twig is at its core simply a templating enging for php; it's a skin, an illusion. It replaces the old style <?php echo date('Y-m-d'); ?> commonly used in php. This means two things:
Twig statements are executed server-side
Twig can access (most) php's native function
So in order to set a global variable with today's date, you can imply add the following line:
{% set today = date() %}
If you want to have today be available every template, simply set it in your base.twig.html template. Alternatively you can also use the function only when needed.
Set it as a class property. Eg
class DefaultController extends Controller
{
private $now = new \DateTime();
public function page1Action()
{
$this->render('...', ['now'=>$this->now]);
}
public function page2Action()
{
$this->render('...', ['now'=>$this->now]);
}
}
one possibility is to create variable in session like this.
$session = $this->get('session');
$session->set('var', $my_variable);
in another controller you just get it like this
$session->get('var');
in twig you can get your variable
{% app.session.get('var') %}
it can resolve your issue and it is avalaible for a user not globally.
I have a question about Symfony 2.
I would like to know how if there is a function implemented in Symfony 2 who return the content mime-type ?
Why mime-type cause trouble ? i have some file and i dont want everyone access to it then i made a methode who check if you have the right to access to this ressource.
chdir("Directory/".$nameoftheressource);
$file = file_get_contents($nameoftheressource);/**/
$namearray=explode(".", $nameoftheressource);
$extension=end($namearray);
$returnFile= new Response();
$returnFile->setContent($file);
if($extension == "css" )
{ $returnFile->headers->set('Content-Type', 'text/css');
return $returnFile;}
Thanks to you xabbuh this is near to work perfectly and as u said saved lot of time
now the code look like
EDIT
use Symfony\Component\HttpFoundation\BinaryFileResponse;
//some code
return new BinaryFileResponse('/Directory/'.$nameoftheressource);
But now it does display the css file but propose me to download it bt i would like to display it as a css normal css file
You can save a lot of code by using the BinaryFileResponse class which among other things automatically adds the right content type header.
It seems that you want to serve a protected CSS file. In this case, you can use the following code and protect the access to this controller using the Symfony Security system:
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
class DefaultController extends Controller
{
/**
* #Route("/css/app.css", name="css")
* #Security("has_role('ROLE_ADMIN')")
*/
public function renderCss()
{
$cssFilePath = $this->container->getParameter('kernel.root_dir').'/data/app.css';
$cssContent = file_get_contents($cssFilePath);
return Response($cssContent, 200, array('Content-Type' => 'text/css'));
}
}
I do have a twig extension which has a method that uses another method from a different controller to render a json output via dependency jsonResponse.
How can I render a controller within a twig extension?
The following code below doesn't seem to work, because render() needs a view file instead of a controller. And I am now referencing to a controller.
class AreaExtension extends \Twig_Extension {
public function add()
{
$outputJson = $this->container->get('templating')->render(new ControllerReference('CMSCoreBundle:Area:index'));
}
}
$ref = new ControllerReference('CMSCoreBundle:Area:index');
$this->handler->render( $ref, 'inline', $options );
Where $this->handler is the fragment.handler service.
In your case:
$outputJson = $this->container->get('fragment.handler')->render(new ControllerReference('CMSCoreBundle:Area:index'));
You can find a full example in this symfony twig extension, see:
https://github.com/symfony/symfony/blob/4.1/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php#L28
and
https://github.com/symfony/symfony/blob/4.1/src/Symfony/Bridge/Twig/Extension/HttpKernelRuntime.php#L41
i want to use the php stripslashes function inside a twig template but this function is not a standard twig function, so i have to add it to twig as an extension, i tried this code inside a controller, but it doesnt work:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class XController extends Controller
{
public function YAction($page)
{
$twig=$this->get('twig');
$twig->addFunction('functionName', new Twig_Function_Function('someFunction'));
...
do i need a use statement for the "Twig_Function_Function" class?
am i doing this wrong?
If you want to use it in your twig templates, you don't need to make any add or call inside your controller, Read the How to write a custom Twig Extension section of the documentation.
Basicaly, you need to create an Extension Class that extends \Twig_Extension , then you need to register it as a service using the twig.extension tag. And finally you need to implement the getFunctions() method in order to add customized twig functions.
But in your case better is to add a filter, with the same logic you can also add a getFilters() method in your extension class so that you can specify your customized filters.
Also, take a deeper look at the Extending Twig section of the documentation to understand all the ways twig can be extended.
Or {{ function('stripslashes', "This\\'ll do") }}
(or apply stripslashes() when building your Twig context)
But, also, if you do this in php:
add_filter('timber/twig', function(\Twig_Environment $twig) {
$twig->addFunction(new Twig\TwigFunction('stripslashes', 'stripslashes'));
return $twig;
});
Then this works in twig:
{{ stripslashes("This\'ll do...") }}
So I'm pretty new to Symfony2 and I'm trying to use the camelize filter in a twig template. However when I request the page I get an error saying that the filter doesn't exist:
The filter "camelize" does not exist in ::base.html.twig
Here's the line from my template file:
{{ 'hello world' | camelize }}
The filter is listed on Twig's quick reference page.
I'm confused, doesn't Symfony2 support all of twig's filters? There seem to be quite a few missing, why? And if it doesn't support them, then is there any way to add the missing ones in?
Thanks in advance!
edit Ok, so it turns out I'm retarded and I need to remember to check that I've actually got the right git project. No wonder I was confused. Thanks replies!
Symfony 2 has title filter for camel case use
{{ entity.yourstring | title }}
to camel case your string
Your link points to a fork on GitHub, meaning a modified copy of the original project. The original project is https://github.com/fabpot/Twig.
There is no camelize filter in Twig. Built-in filters are here. You can write your own camilize filter (it's easy, actually...) following this tutorial: How to write a custom Twig Extension.
EDIT: just for fun, you can write something like:
class MyTwigExtension extends Twig_Extension
{
public function getFilters()
{
return array(
'camelize' => new Twig_Filter_Method($this, 'camelizeFilter'),
);
}
public function camelizeFilter($value)
{
if(!is_string($value)) {
return $value;
}
$chunks = explode(' ', $value);
$ucfirsted = array_map(function($s) { return ucfirst($s); }, $chunks);
return implode('', $ucfirsted);
}
public function getName()
{
return 'my_twig_extension';
}
}
Note that this is a quick and dirty filter! Take a look at the built-in filters to learn best practice!
The filter you're looking for is named "title": http://twig.sensiolabs.org/doc/filters/title.html
Here is the best solution by default in Craft CMS 3
Craft 3 now has a |camel filter for twig
https://docs.craftcms.com/v3/dev/filters.html#camel
{{ 'foo bar'|camel }}
{# Output: fooBar #}