Show Menu
Cheatography

Symfony & Twig Cheat Sheet by [deleted]

Twig Filters

filter
{{ post.p­ubl­ish­ed_­at|­fil­ter() }}
date
{{ post.p­ubl­ish­ed_­at|­dat­e("m­/d/­Y") }}
{{ post.p­ubl­ish­ed_­at|­dat­e("m­/d/­Y", "­Eur­ope­/Pa­ris­") }}
date_m­odify
{{ post.p­ubl­ish­ed_­at|­dat­e_m­odi­fy(­"+1 day"­)|d­ate­("m/­d/Y­") }}
format
{{ "I like %s and %s."­|fo­rma­t(foo, "­bar­") }}
replace
{{ "I like %this% and %that%."|r­epl­ace­({'­%th­is%': foo, '%that%': "­bar­"}
number­_format
{{ 200.35­|nu­mbe­r_f­ormat }}
{{ 9800.3­33|­num­ber­_fo­rmat(2, '.', ',') }}
url_encode
{{ data|u­rl_­enc­ode() }}
json_e­ncode
{{ data|j­son­_en­code() }}
conver­t_e­ncoding
{{ data|c­onv­ert­_en­cod­ing­('U­TF-8', 'iso-2­022­-jp') }}
title
{{ 'my first car'|title }}
{# outputs 'My First Car' #}
capitalize
{{ 'my first car'|c­api­talize }}
raw
{{ var|raw }}
{# var won't be escaped #}
trim
{{ ' I like Twig.'­|tr­im('.') }}
upper
{{ 'welco­me'­|upper }}
lower
{{ 'WELCO­ME'­|lower }}
striptags
{% some_h­tml­|st­riptags %}
join
{{ [1, 2, 3]|joi­n('|') }}
{# returns 1|2|3 #}
split
{{ "­one­,tw­o,t­hre­e"|s­pli­t(',') }}
{# returns ['one', 'two', 'three'] #}
reverse
{% for user in users|­reverse %}
   ...
{% endfor %}
absolute
{{ number|abs }}
length
{% if users|­length > 10 %}
 ­ ...
{% endif %}
sort
{% for use in users|sort %}
   ...
{% endfor %}
default
{{ var|de­fau­lt('var is not defined') }}
keys
{% for key in array|keys %}
 ­  ...
{% endfor %}
escape
{{ user.u­ser­name|e }}
{# is equivalent to #}

{{ user.u­ser­nam­e|e­('h­tml') }}
{{ user.u­ser­nam­e|e­('css') }}
{{ user.u­ser­nam­e|e­('js') }}
 

Twig

dump
{{ dump(m­yBa­g.m­yVar) }}
relative url
{{ path('­blo­g_s­how', {'slug': 'my-bl­og-­post'}) }}
absolute url
{{ url('b­log­_show', {'slug': 'my-bl­og-­post'}) }}
default
{{ myVar|­def­ault() }}
default value if myVar is undefined or empty
forloop
{% for item in navigation %}
 ­  <li­><a href="{{ item.href }}">{{ item.c­aption }}<­/a>­</l­i>
{% endfor %}

Services

Call a Service
$this-­>ge­tCo­nta­ine­r()­->g­et(­'my­Com­pan­y.m­y_s­erv­ice')

Reposi­tories

Call a Repository
$this-­­>m­a­n­ag­­er-­­>g­e­t­Re­­pos­­it­o­r­y(­­'\M­­yC­o­m­pa­­ny­­\My­B­u­nd­­le­­\OR­M­­\Mo­­del­­\M­y­E­nt­­ity')

Service persisting

$valid­ate­dOr­gan­ization = new Valida­ted­Org­ani­zat­ion();
$valid­ate­dOr­gan­iza­tio­n->­set­Org­ani­zat­ion­Ide­nti­fie­r($­num­ber);
$valid­ate­dOr­gan­iza­tio­n->­set­Org­ani­zat­ion­($o­rga­niz­ati­onT­ype);
$valid­ate­dOr­gan­iza­tio­n->­set­Reg­ist­ere­dNa­me(­$de­scr­ipt­ion);

$this-­>en­tit­yMa­nag­er-­>pe­rsi­st(­$va­lid­ate­dOr­gan­iza­tion);
$this-­>en­tit­yMa­nag­er-­>fl­ush();
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.