Twig is a template engine for PHP. It parses templates into tags, prints, and blocks. The lexer tokenizes templates into tokens, and the parser converts tokens into an AST. The compiler generates PHP code from the AST. Twig supports tags like for loops and if/else, macros, and internationalization. It can be extended with custom tags, filters, functions. Security features include escaping, sandboxing and permissions. Templates can access objects and be rendered without controllers.
Twig is the template engine used by Drupal 8 and other modern PHP applications. Twig's expressiveness, consistency and secure-by-default policy are still unparalleled among PHP's template engines.
In this session you'll learn advanced techniques, tips and tricks useful for real-world applications and uncommonly used features that will allow you to master Twig.
Twig is the template engine used by Drupal 8 and other modern PHP applications. Twig's expressiveness, consistency and secure-by-default policy are still unparalleled among PHP's template engines.
In this session you'll learn advanced techniques, tips and tricks useful for real-world applications and uncommonly used features that will allow you to master Twig.
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
These are the slides for a workshop I’ve given at a couple conferences, explaining how Twig works to people who don’t necessarily come from a programming background.
TWIG: the flexible, fast and secure template language for PHPCesare D'Amico
TWIG is a template engine created by Fabien Potencier, the father of Symfony. In this talk you'll learn why he wrote it, its main features and strengths.
Building a Pyramid: Symfony Testing StrategiesCiaranMcNulty
The last few years have seen a huge adoption of testing practices, and an explosion of different testing tools, in the PHP space. The difficulties come when we have to choose which tools to use, in what combinations, and how to apply them to existing codebases.
In this talk we will look at what tools are available, what their strengths are, how to decide which set of tools to use for new or legacy projects, and when to prioritise decoupling and testability over the convenience we get from our frameworks.
Full-day tutorial for the dutch php conference 2011 giving a very quick tour around all the various areas of the ZCE syllabus and some tips on the exam styles
All projects start with a lot of enthusiasm. As many projects grow the technical debt gets bigger and the enthusiasm gets less. Almost any developer can develop a great project, but the key is maintaining an ever evolving application with minimal technical debt without loosing enthusiasm.
During this talk you will be taken on the journey of application design. The starting point is an application that looks fine but contains lots of potential pitfalls. We will address the problems and solve them with beautiful design. We end up with testable, nicely separated software with a clear intention.
Performance and testing are just one aspect of code, to really be successful your code needs to be readable, maintainable and generally easier to comprehend and work with. This talk draws from my own experience in applying the techniques of object calisthenics and code readability, within an existing team. It will help you identify trouble areas, learn how to refactor them and train you to write better code in future projects avoiding common pitfalls.
These are the slides for a workshop I’ve given at a couple conferences, explaining how Twig works to people who don’t necessarily come from a programming background.
TWIG: the flexible, fast and secure template language for PHPCesare D'Amico
TWIG is a template engine created by Fabien Potencier, the father of Symfony. In this talk you'll learn why he wrote it, its main features and strengths.
Building a Pyramid: Symfony Testing StrategiesCiaranMcNulty
The last few years have seen a huge adoption of testing practices, and an explosion of different testing tools, in the PHP space. The difficulties come when we have to choose which tools to use, in what combinations, and how to apply them to existing codebases.
In this talk we will look at what tools are available, what their strengths are, how to decide which set of tools to use for new or legacy projects, and when to prioritise decoupling and testability over the convenience we get from our frameworks.
Full-day tutorial for the dutch php conference 2011 giving a very quick tour around all the various areas of the ZCE syllabus and some tips on the exam styles
All projects start with a lot of enthusiasm. As many projects grow the technical debt gets bigger and the enthusiasm gets less. Almost any developer can develop a great project, but the key is maintaining an ever evolving application with minimal technical debt without loosing enthusiasm.
During this talk you will be taken on the journey of application design. The starting point is an application that looks fine but contains lots of potential pitfalls. We will address the problems and solve them with beautiful design. We end up with testable, nicely separated software with a clear intention.
Twig for Drupal @ Frontendunited Amsterdam 2012Rene Bakx
The slides for the Twig for Drupal 7 introduction talk I gave at FrontendUnited in Amsterdam.
No hardcore coding, just examples why Twig is for HTML was SASS is for your CSS.
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfARORACOCKERY2111
Summary
HW6: Account Management
In HW4, you kept track of multiple usernames and its associated password using arrays.
However, usernames and passwords are typically part of a “User” object which in turn may be
part of an “Account” object. Accounts also typically require a certain level of security beyond
the typical encryption mechanisms. This assignment goes deeper into the concept of OOP as you
create objects that requires proper rules and scope for correct usage.
Aside: As with Item objects from HW5, Account and User data is typically stored in databases.
Skills Expected
? All the skills from previous Assignment(s)
? Accessors/Mutators
? Overriding methods: equals and toString
Assignment Description
You will write three Class objects and a Driver for each class (i.e. submit six .java files):
? User
? Account
? AccountList
Note: All properties MUST be private
Submission Requirement: The Driver Class
? Each Class designed MUST be submitted with a corresponding “Driver” Class
? The Driver Class should have a main() that demonstrates, at minimum
o Calling the appropriate constructor to create the appropriate instance
o Everyproperty(instancevariables)canbesetandgetcorrectly(whereallowed) ? Every public
method can be called successfully (and return the correct result)
Class Design: User
The User class is intended to be an abstract and simplified representation of a user
Class Properties
? First Name (String)
? Last Name (String)
? Username (String)
? Password (String)
Class Invariant
? First and Last Name must not be empty
? Username must be at least four characters long
? Password must be at least four characters long (is this a good invariant?)
Class Components
? A constructor that sets the initial user data (first name, last name, username, password)
? A getter/setter for each properties set out above
? A toString() method
? An equals() method
Class Design: Account
The Account class is intended to be an abstract and simplified representation of an account
Class Properties
? User (User)
? Balance (double) – represents how much money the user has in the account
Class Invariant
? Must be a valid account
? Balance must not be negative
Class Components
? A constructor that sets the initial User instance and balance amount
? A Getter but not a Setter for the each properties set out above (why?)
? A public method to add to the balance
? A public method to withdraw from the balance
? A toString() method
? An equals() method
Class Design: AccountList
The AccountList class is intended to be an abstract and simplified representation of a list of
accounts.
Class Properties
? Accounts (an array of Account objects – or ArrayList) o No getters or setters* (do you know
why?)
Class Invariant
? Can’t have multiple accounts with the same username
Class Components
? A public method that adds new accounts
? A public (boolean) method that determines whether an account with a given username exists in
the list
Grading Criteria
? User class object
o [2 points] Impl.
Using the Tooling API to Generate Apex SOAP Web Service ClientsSalesforce Developers
Join us as we review the capabilities of the existing WSDL-to-Apex code generation feature, and explain how we built a tool to provide expanded features using the Tooling API. The resulting tool has greater support for more WSDL features, generates test cases and the associated mocks to maximize code coverage, and optionally includes HttpRequest versions of the callouts.
Обработчик шаблонов Twig обретает все большую популярность среди разработчиков. Он поддерживается практически всеми современными PHP фреймверками: Drupal, Symfony, Zend Framework, YII, CodeIgniter, CakePHP. Так за что разработчики любят Twig?
В докладе автор на примерах покажет простоту и гибкость Twig шаблонизатора. Далее будут рассмотрены некоторые аспекты расширения стандартного Twig функционала при помощи собственных функций, фильтров, тестов, декларирования глобальных переменных и т.д. Также будет показано внутренне устройство Twig – парсер, лексер, компилятор и создание собственного тега (то что пишется между {%..%} )
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
Welcome to the first live UiPath Community Day Dubai! Join us for this unique occasion to meet our local and global UiPath Community and leaders. You will get a full view of the MEA region's automation landscape and the AI Powered automation technology capabilities of UiPath. Also, hosted by our local partners Marc Ellis, you will enjoy a half-day packed with industry insights and automation peers networking.
📕 Curious on our agenda? Wait no more!
10:00 Welcome note - UiPath Community in Dubai
Lovely Sinha, UiPath Community Chapter Leader, UiPath MVPx3, Hyper-automation Consultant, First Abu Dhabi Bank
10:20 A UiPath cross-region MEA overview
Ashraf El Zarka, VP and Managing Director MEA, UiPath
10:35: Customer Success Journey
Deepthi Deepak, Head of Intelligent Automation CoE, First Abu Dhabi Bank
11:15 The UiPath approach to GenAI with our three principles: improve accuracy, supercharge productivity, and automate more
Boris Krumrey, Global VP, Automation Innovation, UiPath
12:15 To discover how Marc Ellis leverages tech-driven solutions in recruitment and managed services.
Brendan Lingam, Director of Sales and Business Development, Marc Ellis
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
3. Twig's three tags
Twig parses just three simple tags:
{# comment tag - aren't rendered and they are also
multi-line
#} – do nothing!
{{ 'print tag' }}
– say something!
{% set this = 'block tag' %}
- do something!
4.
5.
6. The Lexer
The lexer tokenizes a template source code into a token stream. The default
lexer recognizes 13 different token types.
Here is the output for the Hello {{ name }} template:
TEXT_TYPE(Hello )
VAR_START_TYPE()
NAME_TYPE(name)
VAR_END_TYPE()
EOF_TYPE()
7. The Parser
The parser converts the token stream into an AST (Abstract Syntax Tree), or
a node tree. The core extension defines the basic nodes like: for, if, ... and the
expression nodes.
Here is the output for the Hello {{ name }} template:
Twig_Node_Module(
Twig_Node_Text(Hello )
Twig_Node_Print(
Twig_Node_Expression_Name(name)
)
)
9. The Compiler
The last step is done by the compiler. It takes a node tree as an input and
generates PHP code usable for runtime execution of the template.
The generated template for a Hello {{ name }} template reads as follows:
/* Hello {{ name }} */
class __TwigTemplate_1121b6f109fe93ebe8c6e22e3712bceb extends Twig_Template
{
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "Hello ";
echo twig_escape_filter($this->env, $this->getContext($context, "name"), "html", null,
true);
}
// some more code
}
13. FOR Loops
{% for user in users %}
{{user.name}}
{% else %}
{{ ‘No users’ }}
{% endfor %}
{% for i in 0..10 %}
{% for l in 'a'..'z' %}
{% for l in 'a'|upper..'z'|upper %}
{% for i in 0|range(10, 2) %}
{% for blog in blogs %}
<div class="link {{ cycle(['even', 'odd'], loop.index0) }}">
{{ blog.description }}
</div>
{% endfor %}
14. IF Tag
Multiple branches:
{% if kenny.sick %}
Kenny is sick.
{% elseif kenny.dead %}
You killed Kenny! You bastard!!!
{% else %}
Kenny looks okay --- so far
{% endif %}
Ternary operator:
{{ human.alive ? ‘It’s alive’ : ‘Wasted’ }}
15. - define a macro in a separate twig file:
- include your reusable macro where you want:
MACROS - a reusable and configurable
snippet of HTML
17. Spaceless
Use the spaceless tag to remove whitespace between HTML tags, not
whitespace within HTML tags or whitespace in plain text:
{% spaceless %}
<div>
<strong>foo bar</strong>
</div>
{% endspaceless %}
{# output will be <div><strong>foo bar</strong></div> #}
{% set value = 'no spaces' %}
<li> {{- value }} </li>
{# outputs '<li>no spaces </li>' #}
18. Verbatim
The verbatim tag marks sections as being raw text that should not be parsed.
For example to put Twig syntax as example into a template you can use this
snippet:
{% verbatim %}
<ul>
{% for item in seq %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endverbatim %}
You can also use this tag to avoid the conflict with the default angular.js syntax,
if you do not want to change it.
19. The i18n extension
To use it, first, install the Extensions library.
You need to register this extension before using the trans block, then configure
the gettext extension:
// Set language to French
putenv('LC_ALL=fr_FR');
setlocale(LC_ALL, 'fr_FR');
// Specify the location of the translation tables
bindtextdomain('myAppPhp', 'includes/locale');
bind_textdomain_codeset('myAppPhp', 'UTF-8');
// Choose domain
textdomain('myAppPhp');
{% trans "Hello World!" %}
{% trans string_variable %}
{% trans %}
Hello {{ name }}
{% endtrans %}
21. Setting your own custom syntax
You may want to use simultaneously the default syntax of
angular( {{ }} ) with twig - what to do?
Change the twig default syntax to your preferred one!
22. Creating a TWIG extension
Twig is very customizable, and allows you to create custom tools, like tags,
filters, operators, functions by extending the core(libtwigExtensionCore.php) .
The principle of creating an extension is the same for any element you
wish to customize: you create a class which extends the Twig_Extension
abstract class, then overwrite the desired function, and inject your service or
create a custom function which you intend to use in the templates.
23. use it in your templates:
{{ entityHelper.attributeByStore(promo, attribute) }}
24. Sandbox
• It’s a regular Twig extension, {% sandbox %}
• Disabled by default.
• It allows to restrict the functions, filters, tags and object properties used in the
templates.
• It’s based on security policies.
$loader = new Twig_Loader_Filesystem('...');
$twig = new Twig_Environment($loader, array());
$properties = array(‘User’ => array('name', 'address'));
$policy = new Twig_Sandbox_SecurityPolicy(
array(), array(), array(), $properties, array()
);
$sandbox = new Twig_Extension_Sandbox(
$policy, true // all templates are sandboxed
);
$twig->addExtension($sandbox);
25. The template now displays an error:
{% sandbox %}
{% include 'user.html' %}
{% endsandbox %}
{{ user.name }} - ok
{{ user.address }} - ok
{{ user.age }} - is not accessible
Whoops, looks like something went wrong.
User: {{ user.age }}
Calling "age" property on a "User" object is not allowed …
26. Security policy arguments:
$policy = new Twig_Sandbox_SecurityPolicy(
$tags,
$filters,
$methods,
$properties,
$functions
);
Allow just 3 filters:
$policy = new Twig_Sandbox_SecurityPolicy(
$tags,
array('escape', 'upper', 'lower'),
$methods,
$properties,
$functions
);
27. {{ include }} vs {% include %}
1) If you want to store contents of a file in a variable if you want to repeat it twice:
{% set content = include('test.twig') %}
Instead of:
{% set content %}
{% include 'test.twig' %}
{% endset %}
2) If you want to add filters:
{{ include('alert.twig') | upper }}
Its tag equivalent:
{% set temp %}
{% include 'alert.twig' %}
{% endset %}
{{ temp | upper }}
Also, according to the documentation, it looks recommended to use {{ include() }} to
fit with best practices.
28. Conditional layouts
{% extends request.ajax ? "base_ajax.html" : "base.html" %}
{% block content %}
This is the content to be displayed.
{% endblock %}
Dynamic inclusion of a template:
{% include var|default('index') ~ '_foo.html' %}
29. Accessing an object attribute
{{ user.name }}
name can be:
* an item on an array
* property on an object
* getName()
{{ user[‘name’] }}
or you can force it to *just* fetch “name” as an array
item