Création d'une extension Twig de filtre personnalisé
14 12 2016
20 commentaires
On a souvent besoin des filtres Twig pour mettre en forme les objets dans les templates. Voici la liste officielle des filtres Twig existants.
Cependant quand les filtres Twig existants ne suffisent pas, on peut avoir recourt à la création d'une extension de filtre Twig personnalisé.
Par exemple pour les sites e-commerce, on a besoin d'un filtre qui calcule la TVA d'un produit affichant un prix HT afin de calculer le montant TTC (rappel : prix HT + TVA = prix TTC). Car en effet sur un site e-commerce tous les prix des produits rentrés en base sont obligatoirement HT.
Création d'un filtre personnalisé de calcul de la TVA
On doit tout d'abord créer un dossier Twig/Extension dans le dossier src.
Ce dossier va contenir la classe du filtre que nous allons appeler TvaExtension.php
Nous allons dès maintenant déclarer cette extension en tant que service dans le fichier services.yml
services:
tva:
class: Boutique\BoutiqueBundle\Twig\Extension
\TvaExtension
tags:
- { name: twig.extension }
On déclare donc la classe Boutique\BoutiqueBundle\Twig\Extension
\TvaExtension et on précise dans les tags que c'est une extension Twig en écrivant - { name: twig.extension } (sinon le filtre Twig ne marchera pas)
Maintenant occupons-nous du fichier TvaExtension.php.
<?php
namespace Boutique\BoutiqueBundle\Twig
\Extension;
class TvaExtension extends \Twig_Extension
{
public function getFilters() //méthode obligatoire pour nommer le filtre dans twig
{
return array(new \Twig_SimpleFilter('tva', array($this,'calculTva')));//on nomme simplement le filtre que l on va utilisé dans twig. On le nome tva et on lui associe la méthode calculTva
}
function calculTva($prixHT,$tva) //définition de la méthode principale du filtre tva
{
$prixTTC = round($prixHT/$tva,2);
return $prixTTC;
}
public function getName() //méthode obligatoire pour nommer le filtre dans twig
{
return 'tva_extension';
}
}
Et maintenant on peut appliquer dans le template le filtre à la variable {{produit.prix}}
{{produit.prix|tva(produit.tva.multiplicate)| number_format(2, '.', ',')}} €
Attention il y a un ordre pour les paramètres de la méthode calculTva($prixHT,$tva). on définit les parametre de la vue : le premier parametre est produit.prix et le deuxieme parametre est produit.tva.muliplicate
produit.tva.muliplicate étant le multiplicateur de la TVA contenu dans une entité Tva lié à Produits en n..1 et ayant comme attribut multiplicate avec par exemple une valeur égale à 0.833 (pour la TVA à 20%).
Pour obtenir le coefficient multiplicateur c'est de la gestion : on fait coeff = prix HT/prix TTC=0.833 (pour la TVA à 20%)
catégorie: Twig
Commentaires
https://briansclub.vip
Heya! I know this is somewhat off-topic however I had to ask.
Does running a well-established blog like yours take a massive amount work?
I'm completely new to writing a blog however I do write in my journal on a daily basis.
I'd like to start a blog so I will be able to share my personal experience and
feelings online. Please let me know if you
have any recommendations or tips for brand new aspiring blog
owners. Thankyou!
https://brainsclub.store
Howdy! I know this is kinda off topic but I'd figured I'd ask.
Would you be interested in exchanging links or maybe guest writing a
blog article or vice-versa? My blog discusses a lot of the same subjects as
yours and I believe we could greatly benefit from each other.
If you might be interested feel free to shoot me an e-mail.
I look forward to hearing from you! Fantastic blog by the way!
https://briansclubcc.cm
Hi there i am kavin, its my first time to commenting anyplace,
when i read this article i thought i could also make comment due
to this good paragraph.
https://briansclub.live
I think the admin of this web site is actually working hard for his site, since here
every information is quality based data.
https://briansclubs.live
Pretty! This has been a really wonderful article. Thank you for providing these details.
https://briansclub.ws/
This article will help the internet viewers for creating new webpage or
even a blog from start to end.
https://briansclubcm.shop
Have you ever thought about including a little bit more than just your articles?
I mean, what you say is important and all. However imagine if you added some great
photos or video clips to give your posts more, "pop"!
Your content is excellent but with pics
and videos, this blog could definitely be one of the most beneficial in its niche.
Good blog!
https://floodcrm.ru/
What i don't realize is in truth how you are no longer actually much more smartly-appreciated
than you might be right now. You're so intelligent.
You realize thus significantly when it comes to this subject,
produced me personally believe it from numerous various angles.
Its like men and women aren't interested except it is one thing to accomplish with Girl gaga!
Your own stuffs outstanding. All the time
take care of it up!
https://vclub-cc.ru/
I was able to find good information from your articles.
https://vclub.jp/
This is really interesting, You are a very skilled blogger.
I have joined your rss feed and look forward to seeking more of
your magnificent post. Also, I have shared your web site in my social networks!
https://vclubshop.rs/
Hello there, just became alert to your blog through Google, and found that it is truly informative.
I'm going to watch out for brussels. I'll be grateful if you continue this in future.
Many people will be benefited from your writing. Cheers!
https://dcshop.ws
Fine way of telling, and pleasant article to get information concerning my presentation subject, which
i am going to deliver in school.
https://vclub.bz/
Awesome things here. I'm very happy to look your post. Thank you so much and I am
taking a look ahead to contact you. Will you kindly
drop me a e-mail?
https://vclubcc.ru/
Saved as a favorite, I love your blog!
https://briansclub.shop
Ahaa, its good discussion concerning this article here at this weblog, I have read all that, so now me also commenting here.
https://vclubshop.plus/
It's truly very complex in this active life to listen news on Television, thus I only use web for that purpose, and obtain the hottest news.
https://bclub.vin
Hey there! I've been reading your blog for a while now and
finally got the bravery to go ahead and give you a shout out
from Houston Tx! Just wanted to say keep up the excellent work!
https://briansclub.ski/
You really make it seem so easy along with your presentation however
I find this topic to be actually something that I feel I would never understand.
It kind of feels too complicated and extremely large for me.
I am having a look ahead for your next put up, I will try to get the hold of it!
https://briansclub.kz/
Hello, i think that i saw you visited my web site thus i came
to “return the favor”.I'm attempting to find things to enhance
my website!I suppose its ok to use some of your ideas!!
https://brianclubcc.cm Incredible points. Solid arguments. Keep up the good effort. posté le 24/06/2024 à 19:16
https://brianclubcc.cm
Incredible points. Solid arguments. Keep up the good effort.