twig in symfony

Post on 18-Jul-2015

96 Views

Category:

Software

5 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Twig in symfony

План1. Призначення шаблонізатора twig2. Основи twig (демонстрація standalone twig)

a. Основи розмітки засобами twigb. поняття блоків, extend, include, render (in symfony)c. поняття хелперу та функції в twigd. Оператори розгалуження та циклів у twig

3. Викристання twig в symfony2 (демонстрація)4. Розробка власної функції та фільтра в twig5. Приклад використання twig_js

Two Step View pattern

Transform View model data -> logical presentation

no specific formatting, may be html, xml, json, arrays, etc

Template Viewlogical presentation -> Physical representation

html layout

Призначення шаблонізатора twig

<!DOCTYPE html><html> <head> <title>My Webpage</title> </head> <body> <ul id="navigation"> {% for item in navigation %} <li><a href="{{ item.href }}">{{ item.caption }}</a></li> {% endfor %} </ul>

<h1>My Webpage</h1> {{ a_variable }} </body></html>

1. розділення верстки та коду2. перетворення масивів даних у html-текст 3. повторне використання фрагментів

(шаблонів) html-коду4. виведення форм

Основи розмітки засобами twig

виведення:<a href="{{ url }}">{{ text }}</a>

обчислення та логіка:{% set foo = 'foo' %}

{% set flag = false %}

{% if flag == true %}

<h3>Sometext</h3>

{% endif %}

{# Коментарі #}

План демонстрації standalone twig (github link)- встановлення twig через composer - Ініціалізація і конфігурація - Створення cache, конфігурація, відключення- Скачування готового шаблона - корекція посилань на ассети (img, css, js)- layout.html.twig розмітка на блоки - index.html.twig заміна блоку content- приклад циклу (відображення масиву даних)- приклад include іншого шаблону в циклі

Поняття блоків twighttp://twig.sensiolabs.org/doc/functions/block.html <title>{% block title %}{% endblock %}</title>

<h1>{{ block('title') }}</h1>

{% block body %}

{% endblock %}

Поняття блоків (перезавантаження)

{% extends "base.html" %}

{% block title %}new title{% endblock %}{% block content %}new content{% endblock %}

Поняття фільтрів та функцій

filters:{{ users|length }}functions: {{ date(user.created_at) }}

Огляд деяких функцій та фільтрів

abs {{ number|abs }}capitalize {{ 'my first car'|capitalize }}date_modify {{ post.published_at|date_modify("+1 day")|date("m/d/Y") }}format {{ "I like %s and %s."|format(foo, "bar") }}lower {{ 'WELCOME'|lower }}upper {{ 'welcome'|upper }} {# outputs 'WELCOME' #}title {{ 'my first car'|title }} {# outputs 'My First Car' #}template_from_string {{ include(template_from_string("Hello {{ name }}")) }}

Оператор циклу for{% for user in users %}

<li>{{ user.username|e }}</li>

{% endfor %} {# e - shortcut to escape a variable #}

корисні “змінні”:loop.index - # of iterations from the beginning (1 indexed)loop.index0 - # of iterations from the beginning (0 indexed)loop.revindex - # of iterations from the end (1 indexed)loop.revindex0 - # of iterations from the end (0 indexed)loop.first - true if first iterationloop.last - true if last iterationloop.length - # of iterations

only array keys: {% for key in users|keys %} <li>{{ key }}</li>{% endfor %}

keys and values:{% for key, user in users %} <li>{{ key }}: {{ user.username|e }}</li> {% endfor %}

Особливості використання twig в symfony docs Розміщення шаблонів:app/Resources/views/path/to/bundle/Resources/views/

імена шаблонів:AcmeBlogBundle:Blog:index.html.twig

План демонстрації symfony (gh link)- розмістити той же index з шаблона у

layout.html.twig, ассети - у відпов. папки- пофіксити посилання на ассети (css, js,

images)- створити декілька раутів (використовуючи

існуючий контролер), додати ссилки у менюшку, змінити урл в конфігурації, @Template annotations

- sub-render для квартир- власний twig-фільтр dotdotdot

підключення ассетів (+app/config.yml){% stylesheets 'bundles/app/css/*' filter='cssrewrite' %}

<link rel="stylesheet" href="{{ asset_url }}" />

{% endstylesheets %}

{% javascripts

'@AppBundle/Resources/public/js/*'

'@AcmeBarBundle/Resources/public/js/form.js'

'@AcmeBarBundle/Resources/public/js/calendar.js' %}

<script src="{{ asset_url }}"></script>

{% endjavascripts %}

{% image '@AppBundle/Resources/public/images/example.jpg' %}

<img src="{{ asset_url }}" alt="Example" />

{% endimage %}

app.security - The security context.app.user - The current user object.app.request - The request object.app.session - The session object.app.environment - The current environment (dev, prod, etc).app.debug - True if in debug mode. False otherwise.

Використання routing в twig

- створити новий раут- додати відповідний action до контролеру- створити шаблон- додавати посилання path("_routename")

sub-render- створити повноцінний action в контролері- рендер цього action’а можна викликати в шаблоні:

<div id="sidebar"> {{ render(controller( 'AcmeDemoBundle:Welcome:view', { 'max': 3 } )) }}</div>

Створення власного фільтрадоки: standalone twig extension symfony twig extension

- розробка src/Acme/DemoBundle/Twig/Extension/DotDotDotExtension.php- реєстрація

# app/config/services.xml

<parameters>

<parameter key="twig.extension.acme.dotdotdot.class" >Acme\DemoBundle\Twig\Extension\DotDotDotExtension</parameter>

</parameters>

<services>

<service id="twig.extension.acme.dotdotdot" class="%twig.extension.acme.dotdotdot.class%" public="false">

<tag name="twig.extension" />

<argument type="service" id="twig.loader" />

</service>

</services>

twig_js docs twigJsBundle 1. Підключити залежність JmsTwigJSBundle, зареєструвати в AppKernel...2. Підключити ассет:{% javascripts "%kernel.root_dir%/../vendor/jms/twig-js/twig.js" %}

<script language="javascript" src="{{ asset_url }}"></script>

{% endjavascripts %}

{% javascripts "@AcmeDemoBundle/Resources/views/Welcome/roomjs.html.twig"

filter="twig_js, ?yui_js" %}

<script language="javascript" src="{{ asset_url }}"></script>

{% endjavascripts %}

3. юзати в JavaScript:var roomobj = {'price': 111, 'caption': 'some caption','description': 'some

descr', 'size': 445, 'img': 'property_1.jpg'};

var content = Twig.render(roomjs.html, {room : roomobj})

$('.properties_list' ).html(content);

Дякую за увагу!Питання?

mailto: dchabanenko@malkosua.comcallto: d_chabanenko.malkos

top related