HTML PEXESOHTML PEXESO
S TWIGEM A TIMBEREMS TWIGEM A TIMBEREM
Karolína Vyskočilová < >
WordCamp Bratislava 2019, 12. října 2019
karolina@kybernaut.cz
ŠABLONOVACÍ SYSTÉMYŠABLONOVACÍ SYSTÉMY
oddělení aplikační vrstvy od prezenční (PHP vs HTML kód)
do šablony se posílají již zpracovaná data = šablona řeší
pouze správné zobrazení
lepší čitelnost a přehlednost kódu
zjednodušení práce mezi kodérem & programátorem
MVC přístup
nejznámější šablonovací systémy: (Nette),
(Laravel) a (Symfony)
Latte Blade
Twig
2009 Fabien Potencier a team
TWIGTWIG
Symfony
ZÁKLADNÍ SYNTAXE TWIGUZÁKLADNÍ SYNTAXE TWIGU
tisk proměnné nebo výrazu {{ ... }}
vyhodnocení podmínky nebo cyklu (if, for, while) {% ... %}
komentáře {# ... #}
PŘÍKLADPŘÍKLAD
PHP
Twig
<!-- todo list --->
<?php foreach ( $items as $item ) : ?>
<ul class="items">
<li><?php echo $item; ?></li>
</ul>
<?php endforeach; ?>
{# todo list #}
{% for item in items %}
<ul class="item">
<li>{{ item }}</li>
</ul>
{% endfor %}
plugin pro integraci Twigu do WordPressu
2013 Jared Novack, Lukas Gächter, Pascal Knecht, Maciej
Palmowski, Coby Tamayo, Upstatement a další na GitHubu
přidává základní data - třídy Post, Menu, User, Widget apod.
Because WordPress is awesome, but the loop isn’t.
TIMBERTIMBER
Twenty Sixteen (template-parts/content-single.php)
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header><!-- .entry-header -->
<?php twentysixteen_excerpt(); ?>
<?php twentysixteen_post_thumbnail(); ?>
<div class="entry-content">
<?php the_content(); ?>
</div>
Twenty Sixteen (functions.php)
function twentysixteen_excerpt( $class = 'entry-summary' ) {
$class = esc_attr( $class );
if ( has_excerpt() || is_search() ) :
?>
<div class="<?php echo $class; ?>">
<?php the_excerpt(); ?>
</div><!-- .<?php echo $class; ?> -->
<?php
endif;
}
function twentysixteen_post_thumbnail() {
if ( post_password_required() || is_attachment() || !
has_post_thumbnail() ) { return; }
if ( is_singular() ) : ?>
<div class="post-thumbnail">
<?php the_post_thumbnail(); ?>
</div><!-- .post-thumbnail -->
<?php else : ?>
<a class="post-thumbnail" href="<?php the_permalink(); ?>"
aria-hidden="true">
<?php the_post_thumbnail( 'post-thumbnail', array( 'alt'
=> the_title_attribute( 'echo=0' ) ) ); ?>
</a>
<?php endif; // End is_singular()
}
v Twigu
<article id="post-{{ post.ID }}" {{ post.class }}>>
<header class="entry-header">
<h1 class="entry-title">{{ post.title }}</h1>
</header><!-- .entry-header -->
{% if post.preview %}
<div class="entry-summary">
{{ post.preview }}
</div>
{% endif %}
{% if post.thumbnail %}
<img src="{{ post.thumbnail.src }}" srcset={{
post.thumbnail.srcset }} alt={{ post.title }}>
{% endif %}
<div class="entry-content">
{{ post.content }}
</div>
JAK NA TO?JAK NA TO?
INSTALACEINSTALACE
balíček pro Composer composer require
timber/timber
plugin Timber
pro zjednodušení a inspiraci:
z repozitáře
starter theme
PŘIPRAVENÍ DATPŘIPRAVENÍ DAT
běžné WP soubory/šablony, ve kterých se zavolá Twig
načtení globálního kontextu
obsah aktuální stránky/příspěvku přidaný do kontextu
render šablony
$context = Timber::get_context();
$context['foo'] = 'bar';
$context['post'] = new TimberPost();
Timber::render('single.twig', $context);
TWIG ŠABLONYTWIG ŠABLONY
pro zobrazování dat v rámci celé stránky anebo jednotlivých
komponent
HTML layout, který je naplněn daty
přístup ke kontextu => {{ post.title }} zobrazí nadpis
etc.
není možné volat PHP
single.twig
{% extends "base.twig" %}
{% block content %}
<h1 class="big-title">{{foo}}</h1>
<h2>{{post.title}}</h2>
{% if post.thumbnail %}
<img src="{{post.thumbnail.src}}" />
{% endif %}
<div class="body">{{post.content}}</div>
{% endblock %}
CELKOVÉ ROZVRŽENÍ (LAYOUT)CELKOVÉ ROZVRŽENÍ (LAYOUT)
připravení bloků, které budou naplněny jednotlivými
šablonami
předejte se duplicitnímu obsahu
zlepší se konzistence v projektu
použití v rámci layoutu stránky anebo podobných
komponent
base.twig
{% block html_head_container %}
{% include 'header.twig' %}
{% endblock %}
<body class="{{body_class}}">
<div class="wrapper">
{% block content %}
<p>{{__('SORRY! No content found!','your-theme')
</p>
{% endblock %}
</div>
{% include "footer.twig" %}
</body>
</html>
header.twig
footer.twig
<header class="header">
<a href="{{site.url}}" rel="home" class="nav-logo">
<img src="{{ site.theme.link }}/images/logo.svg"
alt="logo">
{% include "menu.twig" with {menu: main_menu.get_items} %}
</a>
</header>
<footer class="footer">
{% include "menu.twig" with {menu: footer_menu.get_items,
custom_class: 'nav--footer'} %}
</footer>
GLOBÁLNÍ DATA A NAPOJENÍ NAGLOBÁLNÍ DATA A NAPOJENÍ NA
ŠABLONUŠABLONU
pomocí třídy Timber
ve starter theme functions.php
/**
* Sets the directories (inside your theme) to find .twig files
*/
Timber::$dirname = array( 'templates', 'views' );
/**
* By default, Timber does NOT autoescape values.
*/
Timber::$autoescape = html;
class StarterSite extends TimberSite {
/** Add timber support. */
public function __construct() {
add_filter( 'timber/context', array( $this,
'add_to_context' ) );
parent::__construct();
}
/** This is where you add some context
*/
public function add_to_context( $context ) {
$context['foo'] = 'bar';
$context['menu'] = new TimberMenu( 'main_menu', array(
'depth' => 2 ) );
return $context;
}
}
new StarterSite();
PŘÍKLADY: MENUPŘÍKLADY: MENU
žádný walker (!)
jednoduchý markup a data z proměnné
menu.twig
{% if menu %}
<ul>
{% for item in items %}
<li class="{{ item.classes | join(' ') }}">
<a href="{{ item.link }}" {{ item.target ? '
target="'~ item.target ~'"' }}>{{ item.title }}</a>
{% include "menu.twig" with {'items': item.children}
%}
</li>
{% endfor %}
</ul>
{% endif %}
PŘÍKLADY: OBRÁZKYPŘÍKLADY: OBRÁZKY
{% if post.thumbnail %}
<img src="{{ post.thumbnail.src }}" class="my-thumb-class" alt="{{
post.title }}" />
{% endif%}
změna velikosti souborů on the fly
<img src="{{ post.thumbnail.src|resize(100, 100) }}" />
změna formátu on the fly
<picture>
<source srcset="{{ post.thumbnail.src|towebp }}"
type="image/webp">
<source srcset="{{ post.thumbnail.src|tojpg }}"
type="image/jpeg">
<img src="{{ post.thumbnail.src|tojpg }}" alt="{{ post.title
}}">
</picture>
<picture>
{% if webp %}
<source type="image/webp" srcset="
{{ image.width >= 248 ?
image.src('thumbnail')|towebp|resize(248) ~' 248w,' }}
{{ image.width >= 320 ? image.src('thumbnail')|towebp ~'
320w,' }}
{{ image.width >= 540 ?
image.src('medium')|towebp|resize(540) ~' 540w,' }}
" sizes="248px"
/>
{% endif %}
<source srcset="
{{ image.width >= 248 ? image.src('thumbnail')|resize(248)
~' 248w,' }}
{{ image.width >= 320 ? image.src('thumbnail') ~' 320w,'
}}
{{ image.width >= 540 ? image.src('medium')|resize(540) ~'
540w,' }}
" sizes="248px"
/>
<img src="{{ image.src('thumbnail') }}" alt="{{alt}}" class="
{{class}}" width="248" height="{{
(image.height/image.width*248)|round(0, 'ceil') }}"/>
</picture>
DALŠI INTEGRACE WPDALŠI INTEGRACE WP
actions & filters
widgets
shortcodes
stránky/příspěvky chráněné heslem
- základ +
ACF
WooCommerce WooCommerce integration for
Timber
CO SE BUDE DO ZAČÁTKU HODIT ZNÁTCO SE BUDE DO ZAČÁTKU HODIT ZNÁT
Z TWIGUZ TWIGU
pro for cyklus (první, poslední etc.)
funkce pro práci s hodnotami (délka, malá písmena)
keep it DRY a
proměnné
proměnné
filtry
makra includes
cheatsheet
KDE ZAČÍT?KDE ZAČÍT?
- Jared Novack
- Ahmad Awais
- CSS
Tricks
Dokumentace - Timber
Dokumentace - Twig
Video tutoriály
Tutoriály
Timber and Twig Reignited My Love for WordPress
Getting Started
Guides
Reference
Upgrade Guides
Timber Docs
Getting Started
Start here if you want to get to know Timber.
SEARCH
TIMBER HOMEPAGE TWIG DOCUMENTATION GETTING STARTED TUTORIALS
You can download the
documentation for
offline reading:
You are reading the documentation for Twig 2.x. Switch to the documentation for Twig 1.x.
Twig Documentation
Read the online documentation to learn more about Twig.
Introduction
Installation
Twig for Template Designers
Twig for Developers
Extending Twig
Twig Internals
Deprecated Features
Twig Recipes
Coding Standards
License
Twig The flexible, fast, and secure
template engine for PHP
ABOUT DOCS DEV
SymfonyWorld SymfonyCloud: The best way to host your Symfony project
SOUVISEJÍCÍ PROJEKTYSOUVISEJÍCÍ PROJEKTY
- namespaces pro Twig (OnTheGoSystems)
- podpora pro __() (OnTheGoSystems)
- Bare bones Twig templating support for WordPress by
Twig Scoper
Twig to WPML
Sprig
Russell Heimlich
DÍKY ZA POZORNOST!DÍKY ZA POZORNOST!
Pokud máte nějaké otázky, tak sem s nimi!
P.S. Rádi vás uvidíme na .WordCamp Praha 2020

HTML pexeso s Twigem a Timberem

  • 1.
    HTML PEXESOHTML PEXESO STWIGEM A TIMBEREMS TWIGEM A TIMBEREM Karolína Vyskočilová < > WordCamp Bratislava 2019, 12. října 2019 karolina@kybernaut.cz
  • 2.
    ŠABLONOVACÍ SYSTÉMYŠABLONOVACÍ SYSTÉMY odděleníaplikační vrstvy od prezenční (PHP vs HTML kód) do šablony se posílají již zpracovaná data = šablona řeší pouze správné zobrazení lepší čitelnost a přehlednost kódu zjednodušení práce mezi kodérem & programátorem MVC přístup nejznámější šablonovací systémy: (Nette), (Laravel) a (Symfony) Latte Blade Twig
  • 3.
    2009 Fabien Potenciera team TWIGTWIG Symfony
  • 4.
    ZÁKLADNÍ SYNTAXE TWIGUZÁKLADNÍSYNTAXE TWIGU tisk proměnné nebo výrazu {{ ... }} vyhodnocení podmínky nebo cyklu (if, for, while) {% ... %} komentáře {# ... #}
  • 5.
    PŘÍKLADPŘÍKLAD PHP Twig <!-- todo list---> <?php foreach ( $items as $item ) : ?> <ul class="items"> <li><?php echo $item; ?></li> </ul> <?php endforeach; ?> {# todo list #} {% for item in items %} <ul class="item"> <li>{{ item }}</li> </ul> {% endfor %}
  • 6.
    plugin pro integraciTwigu do WordPressu 2013 Jared Novack, Lukas Gächter, Pascal Knecht, Maciej Palmowski, Coby Tamayo, Upstatement a další na GitHubu přidává základní data - třídy Post, Menu, User, Widget apod. Because WordPress is awesome, but the loop isn’t. TIMBERTIMBER
  • 7.
    Twenty Sixteen (template-parts/content-single.php) <articleid="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> </header><!-- .entry-header --> <?php twentysixteen_excerpt(); ?> <?php twentysixteen_post_thumbnail(); ?> <div class="entry-content"> <?php the_content(); ?> </div>
  • 8.
    Twenty Sixteen (functions.php) functiontwentysixteen_excerpt( $class = 'entry-summary' ) { $class = esc_attr( $class ); if ( has_excerpt() || is_search() ) : ?> <div class="<?php echo $class; ?>"> <?php the_excerpt(); ?> </div><!-- .<?php echo $class; ?> --> <?php endif; } function twentysixteen_post_thumbnail() { if ( post_password_required() || is_attachment() || ! has_post_thumbnail() ) { return; } if ( is_singular() ) : ?> <div class="post-thumbnail"> <?php the_post_thumbnail(); ?> </div><!-- .post-thumbnail --> <?php else : ?> <a class="post-thumbnail" href="<?php the_permalink(); ?>" aria-hidden="true"> <?php the_post_thumbnail( 'post-thumbnail', array( 'alt' => the_title_attribute( 'echo=0' ) ) ); ?> </a>
  • 9.
    <?php endif; //End is_singular() }
  • 10.
    v Twigu <article id="post-{{post.ID }}" {{ post.class }}>> <header class="entry-header"> <h1 class="entry-title">{{ post.title }}</h1> </header><!-- .entry-header --> {% if post.preview %} <div class="entry-summary"> {{ post.preview }} </div> {% endif %} {% if post.thumbnail %} <img src="{{ post.thumbnail.src }}" srcset={{ post.thumbnail.srcset }} alt={{ post.title }}> {% endif %} <div class="entry-content"> {{ post.content }} </div>
  • 11.
  • 12.
    INSTALACEINSTALACE balíček pro Composercomposer require timber/timber plugin Timber pro zjednodušení a inspiraci: z repozitáře starter theme
  • 13.
    PŘIPRAVENÍ DATPŘIPRAVENÍ DAT běžnéWP soubory/šablony, ve kterých se zavolá Twig načtení globálního kontextu obsah aktuální stránky/příspěvku přidaný do kontextu render šablony $context = Timber::get_context(); $context['foo'] = 'bar'; $context['post'] = new TimberPost(); Timber::render('single.twig', $context);
  • 14.
    TWIG ŠABLONYTWIG ŠABLONY prozobrazování dat v rámci celé stránky anebo jednotlivých komponent HTML layout, který je naplněn daty přístup ke kontextu => {{ post.title }} zobrazí nadpis etc. není možné volat PHP
  • 15.
    single.twig {% extends "base.twig"%} {% block content %} <h1 class="big-title">{{foo}}</h1> <h2>{{post.title}}</h2> {% if post.thumbnail %} <img src="{{post.thumbnail.src}}" /> {% endif %} <div class="body">{{post.content}}</div> {% endblock %}
  • 16.
    CELKOVÉ ROZVRŽENÍ (LAYOUT)CELKOVÉROZVRŽENÍ (LAYOUT) připravení bloků, které budou naplněny jednotlivými šablonami předejte se duplicitnímu obsahu zlepší se konzistence v projektu použití v rámci layoutu stránky anebo podobných komponent
  • 17.
    base.twig {% block html_head_container%} {% include 'header.twig' %} {% endblock %} <body class="{{body_class}}"> <div class="wrapper"> {% block content %} <p>{{__('SORRY! No content found!','your-theme') </p> {% endblock %} </div> {% include "footer.twig" %} </body> </html>
  • 18.
    header.twig footer.twig <header class="header"> <a href="{{site.url}}"rel="home" class="nav-logo"> <img src="{{ site.theme.link }}/images/logo.svg" alt="logo"> {% include "menu.twig" with {menu: main_menu.get_items} %} </a> </header> <footer class="footer"> {% include "menu.twig" with {menu: footer_menu.get_items, custom_class: 'nav--footer'} %} </footer>
  • 19.
    GLOBÁLNÍ DATA ANAPOJENÍ NAGLOBÁLNÍ DATA A NAPOJENÍ NA ŠABLONUŠABLONU pomocí třídy Timber ve starter theme functions.php /** * Sets the directories (inside your theme) to find .twig files */ Timber::$dirname = array( 'templates', 'views' ); /** * By default, Timber does NOT autoescape values. */ Timber::$autoescape = html;
  • 20.
    class StarterSite extendsTimberSite { /** Add timber support. */ public function __construct() { add_filter( 'timber/context', array( $this, 'add_to_context' ) ); parent::__construct(); } /** This is where you add some context */ public function add_to_context( $context ) { $context['foo'] = 'bar'; $context['menu'] = new TimberMenu( 'main_menu', array( 'depth' => 2 ) ); return $context; } } new StarterSite();
  • 21.
    PŘÍKLADY: MENUPŘÍKLADY: MENU žádnýwalker (!) jednoduchý markup a data z proměnné
  • 22.
    menu.twig {% if menu%} <ul> {% for item in items %} <li class="{{ item.classes | join(' ') }}"> <a href="{{ item.link }}" {{ item.target ? ' target="'~ item.target ~'"' }}>{{ item.title }}</a> {% include "menu.twig" with {'items': item.children} %} </li> {% endfor %} </ul> {% endif %}
  • 23.
    PŘÍKLADY: OBRÁZKYPŘÍKLADY: OBRÁZKY {%if post.thumbnail %} <img src="{{ post.thumbnail.src }}" class="my-thumb-class" alt="{{ post.title }}" /> {% endif%}
  • 24.
    změna velikosti souborůon the fly <img src="{{ post.thumbnail.src|resize(100, 100) }}" />
  • 25.
    změna formátu onthe fly <picture> <source srcset="{{ post.thumbnail.src|towebp }}" type="image/webp"> <source srcset="{{ post.thumbnail.src|tojpg }}" type="image/jpeg"> <img src="{{ post.thumbnail.src|tojpg }}" alt="{{ post.title }}"> </picture>
  • 26.
    <picture> {% if webp%} <source type="image/webp" srcset=" {{ image.width >= 248 ? image.src('thumbnail')|towebp|resize(248) ~' 248w,' }} {{ image.width >= 320 ? image.src('thumbnail')|towebp ~' 320w,' }} {{ image.width >= 540 ? image.src('medium')|towebp|resize(540) ~' 540w,' }} " sizes="248px" /> {% endif %} <source srcset=" {{ image.width >= 248 ? image.src('thumbnail')|resize(248) ~' 248w,' }} {{ image.width >= 320 ? image.src('thumbnail') ~' 320w,' }} {{ image.width >= 540 ? image.src('medium')|resize(540) ~' 540w,' }} " sizes="248px" /> <img src="{{ image.src('thumbnail') }}" alt="{{alt}}" class=" {{class}}" width="248" height="{{ (image.height/image.width*248)|round(0, 'ceil') }}"/> </picture>
  • 28.
    DALŠI INTEGRACE WPDALŠIINTEGRACE WP actions & filters widgets shortcodes stránky/příspěvky chráněné heslem - základ + ACF WooCommerce WooCommerce integration for Timber
  • 29.
    CO SE BUDEDO ZAČÁTKU HODIT ZNÁTCO SE BUDE DO ZAČÁTKU HODIT ZNÁT Z TWIGUZ TWIGU pro for cyklus (první, poslední etc.) funkce pro práci s hodnotami (délka, malá písmena) keep it DRY a proměnné proměnné filtry makra includes cheatsheet
  • 30.
    KDE ZAČÍT?KDE ZAČÍT? -Jared Novack - Ahmad Awais - CSS Tricks Dokumentace - Timber Dokumentace - Twig Video tutoriály Tutoriály Timber and Twig Reignited My Love for WordPress
  • 31.
    Getting Started Guides Reference Upgrade Guides TimberDocs Getting Started Start here if you want to get to know Timber. SEARCH TIMBER HOMEPAGE TWIG DOCUMENTATION GETTING STARTED TUTORIALS
  • 32.
    You can downloadthe documentation for offline reading: You are reading the documentation for Twig 2.x. Switch to the documentation for Twig 1.x. Twig Documentation Read the online documentation to learn more about Twig. Introduction Installation Twig for Template Designers Twig for Developers Extending Twig Twig Internals Deprecated Features Twig Recipes Coding Standards License Twig The flexible, fast, and secure template engine for PHP ABOUT DOCS DEV SymfonyWorld SymfonyCloud: The best way to host your Symfony project
  • 34.
    SOUVISEJÍCÍ PROJEKTYSOUVISEJÍCÍ PROJEKTY -namespaces pro Twig (OnTheGoSystems) - podpora pro __() (OnTheGoSystems) - Bare bones Twig templating support for WordPress by Twig Scoper Twig to WPML Sprig Russell Heimlich
  • 35.
    DÍKY ZA POZORNOST!DÍKYZA POZORNOST! Pokud máte nějaké otázky, tak sem s nimi! P.S. Rádi vás uvidíme na .WordCamp Praha 2020