Split function not working in Twig - symfony

what i Need :
Split the string.
i Need first Character from the String.
if the string certain character limit i like to show only first name not by(...).
ex: ankit mishra pandit aggarwaal.
- so i just want only ankit.
- if its is ankit mishra its ok.
* otherwise show Full Name.
Here is the twig code:
{%if item.metadata.name |length < 20 %}
{% set foo = item.metadata.name|split(',') %}
{{ foo[0] }}
{%else%}{{WordLimit(item.metadata.name,20,10)}} ..
{%endif%}
output im getting :
Deepak Singh.
i have refer Source: Twig Split filter http://twig.sensiolabs.org/doc/filters/split.html.
where i have done wrong.

I think the best solution is to write a twig extension.
See http://symfony.com/doc/current/cookbook/templating/twig_extension.html
class AcmeExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('first_word', array($this, 'first_word')),
);
}
public function first_word($word)
{
$words = explode(' ', $word);
$first_word = $words[0];
...
return $first_word;
}
public function getName()
{
return 'acme_extension';
}
}
And if your twig file :
{{item.metadata.name | first_word }}

Related

Include content of CSS file in twig

Let's say I use Webpack, and builded a Css file properly at "build/theme/mail.css".
I wants to include the CONTENT of this File into my twig.
{% include "https://mysite.io/build/theme/mail.css" %} doesn't work saying it can't find the file ( but it exist).
I don't want that because im using an inliner, and absolutly need the #CONTENT in my twig.
Tried the File get Content, didn't works. Found a solution:
twig:
paths:
'%kernel.project_dir%/public': public
Add a twig path to public directory
and then use :
{% apply inline_css(source(theme_asset('#public/build/theme/email.css'))) %}
and add a webpackconfig to build the scss file into public/build
Thanks you all.
You could create custom twig extension and use file_get_contents.
Extension:
<?php
namespace App\Twig;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class GetPublicFileContentExtension extends AbstractExtension
{
/** #var string */
private $publicPath;
public function __construct(ParameterBagInterface $parameterBag)
{
$this->publicPath = $parameterBag->get('kernel.project_dir') . '/public/';
}
public function getFunctions(): array
{
return [
new TwigFunction('get_public_file_content', [$this, 'getPublicFileContent']),
];
}
public function getPublicFileContent(string $filepath)
{
return file_get_contents($this->publicPath . $filepath);
}
}
Twig:
{{ get_public_file_content('build/theme/mail.css') }}

Twig Date Filter Issue | Wrong output

I am working on Symfony application and using Twig for layout.
I facing wrong output issue i google it but can't find the solution.
I have date & time 201801031400 I used this
{{ val.start_date|date("m/d/Y") }}
but get the wrong output 10/27/8364
When i used this {{ "now"|date("m/d/Y") }} it give me correct output
Thanks in Advance!
You need to a function to Twig to achieve this, you can see how to register an extension here
TwigExtension
namespace My/Project/Twig/Extensions
class ProjectTwigExtension extends Twig_Extension {
public function getFunctions() {
return array(
new Twig_SimpleFunction('convert_api_date', function($date) {
return new DateTime($date);
}),
);
}
public function getName() {
return 'ProjectTwigExtension'; //this is mandatory
}
}
twig
{{ convert_api_date('201801031400') | date('d/m/Y') }}
{{ convert_api_date('201801031400') | date('H:i') }}
Above answer will perfectly alright i just my solution code too.
First Twig date filter not support the 201801031400. so for this you have to make your own extension.
How to create twig extension create twig extention
<?php
// src/AppBundle/Twig/AppExtension.php
namespace AppBundle\Twig;
class DateParserFilter extends \Twig_Extension
{
public function getFilters ()
{
return array(
new \Twig_SimpleFilter('parse_date', array($this, 'parseDate'))
);
}
public function parseDate ($string, $formats)
{
if (is_string($formats))
{
$formats = array($formats);
}
foreach ($formats as $format)
{
$dateTime = \DateTime::createFromFormat($format, $string);
if ($dateTime !== false)
{
return $dateTime;
}
}
return $string;
}
public function getName ()
{
return "parse_date";
}
}
after this use your own extension filter first then use twig builtin date filter example show below :)
{{ val.start_date | parse_date(["YmdHi", "d/m/Y H:i"]) | date("M d, Y") }}
Its depend what you have in my case i have [2018][01][03][14][00] = [Y][m][d][H][i]
hope it will help you :)
source of this extension - link
You have to divide your unix timestamp value by 1000.
I'm still not sure with what it's related, but this operation is used by authoritative online converters, that most likely faced the same problem.
I came to this conclusion thanks to this answer Converting a UNIX Timestamp to Formatted Date String.
Below is the proof that your unix timestamp is correct:
1) from www.freeformatter.com
2) from www.epochconverter.com
The data is slightly different due to the time zone. It must be taken into account.
Write in the comments, why should I divide by 1000. I myself will be interested.

Displaying currency symbol in twig

How can I display the currency symbol in twig? I saved the numeric value of the symbol like:
for EURO : €
for DOLLAR: $
When I render these values, & is converted to & and the currency symbol does not show. Any idea will be greatly appreciated. Thank you.
To do it well, you've to add a function or a filter which is called as a helper to render currency symbols within your twig templates.
To use the following function,
{{ currency('en_US') }}
You've to add a twig extension as follow,
xxx.twig.your_extension:
class: XXX\YourBundle\Twig\YourExtension
tags:
- { name: twig.extension }
You've then to add a currency function,
namespace XXX\YourBundle\Twig;
class YourExtension extends \Twig_Extension
{
public function getFunctions() {
return array(
'currency' => new \Twig_Function_Method($this, 'currencyFunction'),
);
}
public function currencyFunction($locale) {
$formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
$symbol = $formatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);
return $symbol;
}
public function getName() {
return 'your_extension';
}
}
I figured it out. When rendering, I need to use the raw filter of twig.
It is an old thread, but for the new people coming here, Twig has now an extension for the currency symbols (with new filters |currency_symbol ) as you can see in the documentation

Twig: show the name of the months based on the current locale

I'm just trying to show the name of the months based on the current locale.
{{ event.date|date('F') }}
but the months are always shown in english...
I have tried this code below I found here, but the result is the same...
class Helper_Twig extends Twig_Extension
{
public function getFilters()
{
return array(
'datetime' => new Twig_Filter_Method($this, 'datetime')
);
}
public function datetime($d, $format = "%B %e")
{
if ($d instanceof \DateTime) {
$d = $d->getTimestamp();
}
return strftime($format, $d);
}
public function getName()
{
return 'Helper';
}
}
NOTE: In the controller I'm checking the current locale using $request->getLocale and it corresponds to the locale parameter I'm switching in parameters.yml.
What is the problem?
Since you defined datetime TwigFilter, you don't have to call {{ event.date|date('F') }}
Instead, you should call this {{ event.date|datetime('%B') }}
You can use SonataIntlBundle to handle localized date representation. Intl library needs to be installed though.
You probably haven't installed the PHP intl-library in your PHP. http://php.net/manual/de/book.intl.php
If you have installed the IntlExtension you can use format_datetime with custom pattern.
{{ event.date|format_datetime(pattern="MMMM") }}
docs:
https://twig.symfony.com/doc/3.x/filters/format_datetime.html
https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax

transfer data in symfony2

I have created two functions in controller of Symfony as follow:
first is newAction
public function newAction()
{
return $this->render('AcmeTaskBundle:Default:index.html.twig');
}
then subAction
public function subAction()
{
echo "hello";
}
I want to use some data from index.html.twig into subAction function.
How I can do that?
All you need is to use
$content = $this->renderView('AcmeTaskBundle:Default:index.html.twig')
This will render contents of template in variable
http://symfony.com/doc/current/book/controller.html#rendering-templates
EDIT according to comment
If you need to render only part of template - then you should refactor your templates.
Exclude that part of code from your index.html.twig into separate template file and include it in index.html.twig:
...
{% include 'AcmeTaskBundle:Default:subpage.html.twig' %}
...
And then in your subAction() call:
$content = $this->renderView('AcmeTaskBundle:Default:subpage.html.twig')

Resources