39,59 €
Master Drupal 8's new Twig templating engine to create fun and fast websites with simple steps to help you move from concept to completion
This book is intended for front-end developers, designers, and anyone who is generally interested in learning all the new features of Drupal 8 theming. Discover what has changed from Drupal 7 to Drupal 8 and immerse yourself in the new Twig PHP templating engine. Familiarity with HTML5, CSS3, JavaScript, and the Drupal Admin interface would be helpful. Prior experience with setting up and configuring a standalone development environment is required as we will be working with PHP and MySQL.
Drupal 8 is an open source content management system and powerful framework that helps deliver great websites to individuals and organizations, including non-profits, commercial, and government around the globe. This new release has been built on top of object-oriented PHP and includes more than a handful of improvements such as a better user experience, cleaner HTML5 markup, a new templating engine called Twig, multilingual capabilities, new configuration management, and effortless content authoring. Drupal 8 will quickly become the new standard for deploying content to both the web and mobile applications. However, with so many new changes, it can quickly become overwhelming knowing where to start and how to quickly.
Starting from the bottom up, we will install, set up, and configure Drupal 8. We'll navigate the Admin interface so you can learn how to work with core themes and create new custom block layouts. Walk through a real-world project to create a Twig theme from concept to completion while adopting best practices to implement CSS frameworks and JavaScript libraries. We will see just how quick and easy it is to create beautiful, responsive Drupal 8 websites while avoiding the common mistakes that many front-end developers make.
Drupal 8 Theming with Twig is intended for front-end developers, designers, and anyone who is generally interested in learning all the new features of Drupal 8 theming. Discover what has changed from Drupal 7 to Drupal 8 and immerse yourself in the new Twig PHP templating engine. Familiarity with HTML5, CSS3, JavaScript, and the Drupal Admin interface would be helpful. Prior experience with setting up and configuring a standalone development environment is required as we will be working with PHP and MySQL.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 387
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: March 2016
Production reference: 1170316
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-873-7
www.packtpub.com
Author
Chaz Chumley
Reviewer
Vincent Lark
Acquisition Editor
Larissa Pinto
Content Development Editor
Onkar Wani
Technical Editor
Pramod Kumavat
Copy Editor
Dipti Mankame
Project Coordinator
Bijal Patel
Proofreader
Safis Editing
Indexer
Rekha Nair
Graphics
Jason Monteiro
Production Coordinator
Aparna Bhagat
Cover Work
Aparna Bhagat
Ever since Chaz can remember, he has been picking up a crayon, a pencil, a pen, or a computer, whether to draw a picture, write a poem, share an article, or develop the next great website. Looking back at these qualities, it's the reason why he chose to use those passions to give back to the open source community. His journey has opened doors to great experiences as a consultant, instructor, trainer, author, web developer, technical architect, Drupalist, and most importantly, a father. However, he could be none of these without first being a student and learning from life, love, and a passion for education, community development, and of course, science and technology.
The sum of these things has allowed Chaz to share his experiences as an active member of the Drupal community, having participated in developing Lynda.com Drupal training videos, authoring multiple Drupal books for Packt Publishing, and giving back his knowledge by contributing numerous articles and presentations at NYCCamp, BadCamp, and DrupalCon, and bringing top-notch Drupal expertise to his clients' work.
However, his greatest journey is still in front of him as he continues to learn new creative ways to architect open source websites, write about the next best things, and laugh with his colleagues along the way.
When I first started this journey of writing a Drupal 8 book, I thought to myself, "what could be so hard about that. Well, let me tell you?" Trying to catch up with every Alpha, Beta, and Release candidate was like chasing that third grade crush around the schoolyard. You were always able to catch her but then she would run again.
Speaking of crushes, I still have one on my beautiful wife. Without her even harder work, dedication, and support, this book would have not been possible. The long hours and lost time cannot be made up, but her smile always fills my heart. She is my friend, colleague in life, love, and spirit. Rebecca has allowed me to grow as an author and pursue the dream of putting my knowledge to pen and paper, even though she will tell you that I have been doing this for a while now ever since I wrote her the first poem. Well honey, I hope you enjoy this latest poem because it's finally published.
I also want to thank my two beautiful children, who while writing this book, have grown up a little bit more. My son Brendan makes me proud every day to be his father and friend. He is a young man in his own mind but always my little buddy, quickly on his way to becoming an Eagle Scout. The other one is my daughter Kayla who is getting ready to go off to college to pursue Graphic Design and just may write a book of her own some day. I definitely look forward to seeing you grow into the beautiful woman you will be.
I would like to thank Colin Panetta and Last Call Media for letting me use the great Drupal 8 chalkboard for the book cover.
I thank the Drupal community without whose support, I wouldn't be working with such an awesome content management framework.
I have to thank my colleagues. There are too many to name but without the absolutely great friends at Forum One I would have lost my mind writing this book: rock star developers, awe-inspiring designers, breathtaking UX, and amazing marketing. Not only is it the best place I have ever worked, we are always hiring!
Vincent Lark is a French Full Stack developer with a strong web development background. After working on frontend and backend software in multiple companies, he's still very interested in every technical part of a product, especially on emergent technologies.
When not coding for work, he also likes developing games as hobby in local game jams.
Vincent previously reviewed other books for Packt Publishing, including Learning JavaScript Data Structures and Algorithms and WebGL Hotshot.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Starting from the bottom, Drupal 8 Theming with Twig will walk you through setting up and configuring a new Drupal 8 website. Navigate across the admin interface, learn how to work with core themes, and create new custom block layouts. Take a real-world project and create a Twig theme that adopts best practices to implement CSS frameworks and JavaScript libraries. See just how quick and easy it is to create beautiful and responsive Drupal 8 websites along with avoiding some of the common mistakes many frontend developers run into.
If you consider yourself a frontend developer, you will be right at home. However, since no PHP knowledge will be necessary, anyone who can create HTML websites with basic HTML5 and CSS3 skills will learn how to create a great Drupal 8 theme.
Chapter 1, Setting up Our Development Environment, will begin with walking you through setting up a development workflow. You will learn how to use an AMP (Apache, MySQL, PHP) stack to configure a local web server. We will introduce the process of installing Drupal 8 and walk through the admin interface in preparation for working with the new Twig templating engine.
Chapter 2, Theme Administration, provides a glance at the Appearance page, where you will learn how to install, uninstall, and configure various themes and settings. We will take a look at the new Block layout system as we explore how to add fields to blocks, reuse blocks, and assign chunks of content to various regions. Learn how Drupal 8 has reconfigured files and folders, where themes are now placed, and how to find core themes.
Chapter 3, Dissecting a Theme, begins with discussing the importance of a proper development environment and the steps involved to ensure that you're ready for Drupal 8. This will help you learn the differences and similarities between core and custom themes and how configuration has changed. Break down the metadata that makes up a theme, libraries, and regions. You will learn the role of templates and how the theme layer interacts with the Twig templating engine.
Chapter 4, Getting Started – Creating Themes, starts with creating a starter theme that allows us to work with assets while learning common techniques to integrate various CSS frameworks. You can learn how to rethink layout strategies as we dive into the theme layer and work with Twig. Then, we will wrap up with creating a subtheme that extends the new Classy base theme.
Chapter 5, Prepping Our Project, covers reviewing a real-world project that we will be building and how to break down how design and functionality should come together in Drupal 8. We will create the new theme structure, define metadata, add regions, and implement several CSS and JavaScript libraries.
Chapter 6, Theming Our Homepage, begins with working with the site branding block to add a logo. We will create a basic HTML wrapper and homepage template using Twig as we convert our homepage mockup into a fully functioning Drupal 8 front page. You will learn how to convert static markup into Twig variables as we theme global components, such as the Search block, menus, and custom blocks. Use the new libraries.yml file to work with assets, such as Twitter Bootstrap and Flex Slider and then attach them to specific templates using the new {{ attach_library() }} function.
Chapter 7, Theming Our Interior Page, will show you how to review mockups and identify what regions, blocks, content types, and views will need to be developed to recreate functionality. You will learn how to reuse Drupal 8 regions, work with the new Page title block, and how Twig plays an important part in rewriting Views output.
Chapter 8, Theming Our Blog Listing Page, starts with the best practice approaches to managing content types. From adding new display modes to enabling and formatting fields, learn how to use content display modes with Views to display data in lieu of using fields directly. You can work with Node templates to add CSS classes directly to our markup, work with content variables, and learn how to suppress fields. You will use Twig filters to format dates and manage individual field templates while creating a listing page.
Chapter 9, Theming Our Blog Detail Page, teaches us how to reuse Twig templates and display different content simply by using file name suggestions to target-specific display modes. You will work with the new comment types to add commenting functionality to pages as fields, learn how to alter comment display using field templates to theme comment threads, and add social sharing functionality to pages using custom blocks and JavaScript libraries that we can attach directly to a block.
Chapter 10, Theming Our Contact Page, introduces contact forms in Drupal 8 that we can use to create fieldable forms that users can interact with. You will learn how to integrate Google Maps into custom blocks that take advantage of library assets and vendor JavaScript.
Chapter 11, Theming Our Search Results, covers core search functionality, how to index database content, and work with search results templates. Core search can sometimes be limited, so we will take a more advanced look at the Search API module to create a better search experience. You will learn how to add individual fields to search and use display modes to output content while creating a Search view that allows us to expose filters to the users to find exactly what they are looking for.
Chapter 12, Tips, Tricks, and Where to Go from Here, introduces how to theme common admin sections of Drupal 8. You will learn how to modify the markup for local tasks and status messages. Reuse Twig templates using extends to share layouts while working with pages and blocks. Finally, we will leave you with some great contributed modules to take a look at and introduce you to the Drupal community.
To follow along with this book, you need an installation of Drupal 8, preferably in a local development environment located on a Windows, Mac, or Linux-based computer. Documentation regarding setting up a local development environment can be found at https://www.drupal.org/setting-up-development-environment. Specific system requirements are listed at https://www.drupal.org/requirements. An introduction to MAMP for Windows and Mac is also covered in Chapter 1, Setting Up Our Development Environment.
To follow along with each lesson, you will need a text editor or IDE. To see a list of software to consider when developing in Drupal 8 you can refer to https://www.drupal.org/node/147789.
Drupal 8 Theming with Twig is intended for frontend developers, designers, and anyone who is generally interested in learning all the new features of Drupal 8 theming. Discover what has changed from Drupal 7 to Drupal 8 and immerse yourself in the new Twig PHP templating engine. Familiarity with HTML5, CSS3, JavaScript, and the Drupal Admin interface would be helpful. Prior experience of setting up and configuring a standalone development environment is required as we will be working with PHP and MySQL.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows "Rename page.html.twig as page--front.html.twig.":
A block of code is set as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Click on the Continue button, which will take us to the license information."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. You can contact the author at http://www.forumone.com/books/drupal-8-theming-with-twig if you are facing a problem with any aspect of this book.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Regardless of you being a seasoned web developer or someone who is just about to start learning Drupal, there are few things that everybody needs to have in place before we can get started:
Let's get started by installing our web environment that we will be using as we take an exciting look at Drupal 8 theming with Twig.
To install and run Drupal 8, our server environment must meet and pass certain requirements. These requirements include a web server (Apache, NGINX, or Microsoft IIS) that can process server-side languages such as PHP, which Drupal 8 is built on.
Our server should also contain a database that can manage the data and content that Drupal 8's content management system will store and process. The preferred database is MySQL. However, Drupal 8 can also support PostgreSQL along with Microsoft SQL Server and Oracle with an additional module support.
Finally, Drupal 8 requires PHP 5.5.9 or later, with the CURL extension.
However, because this book is not meant to be a "How-to" on installing and configuring Apache, MySQL, or PHP, we will take all the guesswork and trial by fire out of the equation and instead turn to MAMP.
MAMP can be found at https://www.mamp.info/en and is a tool that allows us to create Drupal sites locally without the need or knowledge of installing and configuring Apache, MySQL, or PHP on a specific platform.
The application stack will consist of the following:
Let's begin with the steps involved in quickly downloading, installing, and configuring our very own AMP stack along with an initial instance of Drupal that we will be using throughout the rest of this book. Begin by opening up our web browser and navigating to https://www.mamp.info/en/downloads and selecting either Mac OS X or Windows and then clicking on the Download button, as shown in the following image:
MAMP will allow us to install a local web server on either Mac or Windows and provides us with all the tools we will need to develop most open source websites and applications including Drupal 8.
Once the download has completed, we will need to locate the .dmg (Mac users) or .exe (Windows users) installation file and double-click on it to begin the installation process. Once the executable is opened, we will be presented with a splash screen that will guide us through the process of installing and configuring MAMP.
Clicking on the Continue button located on the Introduction pane, will take us to the Read Me information. MAMP will notify us that two folders will be created: one for MAMP and the other for MAMP PRO. It is important to not move or rename these two folders.
Click on the Continue button, which will take us to the license information. Simply accept the terms of the license agreement by clicking on Continue and then on Agree when prompted.
We can finally click on the Install button to complete the installation process. Depending on the operating system, we may need to enter our credentials for MAMP to be able to continue and configure our local web server. Once the install has completed, we can click on the Close button.
Let's begin by opening up MAMP and taking a quick tour of the various settings and how we can go about using our local web server to install and configure a new Drupal 8 instance.
When we first open up MAMP, we will be prompted to launch either MAMP or MAMP PRO, as shown in the following image:
While MAMP is the free version of the local web server, it is strongly recommended that we use MAMP PRO for configuration and easy setup of a website. We can continue by clicking on Launch MAMP PRO, which will prompt us one more time to accept the Initialization of the remaining components that MAMP PRO needs before we can begin using it. Now, click on OK to continue.
We can use MAMP PRO free for 14 days and at the end of that period, we can decide whether to purchase a license or continue using the free version. Click on OK to continue.
If this is the first time you're using MAMP PRO, then there is some quick housekeeping we will want to take care of, beginning with the general settings. MAMP PRO tries to make sure that it does not interfere with any other possible web servers we may be running by setting the default ports of Apache to 8888 and MySQL to 8889. Although this is nice, the recommendation is to click on the Set ports to 80, 443 & 3306 button that will make sure that MAMP PRO is running on more standardized ports for web development.
If we want to make sure that Apache or MySQL are active at all time, we will also check Start Apache and MySQL on system startup and uncheck Stop Apache and MySQL when quitting MAMP PRO. Once we have made these changes, we can click on the Save button. Our changes should now be applied as shown in the following image and MAMP PRO will now prompt us to Start servers now.
The next tab we will look at is the Hosts tab, which is where we will create and configure basic websites. By default, MAMP PRO creates a localhost entry for us, which is common when developing a web application.
We will be using the Hosts tab to create an additional website when we install Drupal 8, so let's take a moment to locate some of the common settings we will need to know. Take a look at the following image; we can see that localhost is the Server name of our default website, uses the default PHP version of 5.6.10, and has a Document root pointing to the htdocs folder of our MAMP installation.
Another nice ability of MAMP PRO is to be able to click on the arrow icon located to the right of the Server name and have our default web browser open up to the localhost page, as shown in the following image:
It is important to point out that the Server name always equates to the name of the URL in our browser that displays our website.
MAMP PRO is quite a robust and powerful local web server and while there are many more configuration options and settings that we could spend time looking through, most of our time will be spent on working from the Hosts tab creating new websites or configure existing sites.
So far, MAMP PRO has configured everything for us, but how to create a new website and, in more general, install a Drupal 8 instance? Let's look at it in the following section.
In order to install Drupal 8 within our local MAMP PRO server, we will need to perform a series of steps:
We will walk through each of these steps in detail to ensure that we all have a copy of Drupal 8 installed properly that we will build upon as we work through each lesson.
Drupal.org is the authority on everything about Drupal. We will often find ourselves navigating to Drupal.org to learn more about the community, look for documentation, post questions within the support forum, or review contributed modules or themes that can help us extend Drupal's functionality. Drupal.org is also the place where we can locate and download the latest release of Drupal 8.
We can begin by navigating to https://www.drupal.org/node/2627402 and locate the latest release of Drupal 8. Click on the compressed version of Drupal 8 that we prefer, which will begin downloading the files to our computer. Once we have a copy of Drupal 8 on our computer, we will want to extract the contents to a location where we can easily work with Drupal and its folders and files.
A document root is the main folder that our host entry will point to. In the case of Drupal, this will be the extracted root folder of Drupal itself. Generally, it is a best practice to maintain some sort of folder structure that is easy to manage and that can contain multiple websites.
For the sake of demonstration, we will create a Sites folder and then copy the compressed Drupal files to our new folder and extract the contents, as shown in the following image:
A host entry represents our website, which, in this case, is our Drupal 8 instance. Hosts always contain a server name that equates to the URL we will use to navigate to Drupal within our browser.
Begin by opening MAMP PRO and clicking on the Hosts tab. To add a new host entry, we can click on the plus icon at the bottom of the Server Name column, as shown in the following image:
By default, this will add a new host entry that will require us to configure with three very important pieces of information:
The General settings for our new host entry should look as shown in the following image:
We can now apply our changes by clicking on the Save button and then clicking on the Yes button when prompted to have MAMP PRO restart the servers.
Drupal 8 requires a database available to install any tables that make up the content management system. These tables will hold configuration data, users and permissions, content, and any extendable functionality that makes Drupal 8 so powerful.
Lucky for us, MAMP PRO installs a MySQL database server that we can take advantage of to create a new database that Drupal 8 can point to. This same database server we will also be working with to back up and restore our database content as we progress through each lesson.
MAMP PRO also installs a free software tool written in PHP for the sole purpose of managing MySQL databases. phpMyAdmin allows us to perform a multitude of tasks from browsing tables, views, fields, and indexes to exporting and importing database backups and much more.
If we switch back over to MAMP PRO, we can locate the MySQL tab and click on the phpMyAdmin link located in the Administer MySQL with region, as shown in the following image:
We should now be presented with phpMyAdmin within our browser. Currently, we are interested in creating a new database. We will revisit phpMyAdmin a little later to learn how to back up and restore our database. The following are the steps to create a database:
We have now created our first MySQL database, which we will use when configuring Drupal 8 in the next step.
Now that we have all of our basic requirements completed, we can open up our favorite web browser and navigate to http://drupal8/core/install.php to begin the installation process.
Since this may be the first time installing Drupal 8, one thing we will notice is that the install screen looks a little different. The install screen has been given a makeover, but the steps are similar to that of Drupal 7, starting with choosing a language.
The installation process will prompt us to choose a language that we want Drupal 8 to be installed in. This language will control how the Admin area appears, and in many cases, the default of English is acceptable. We will need to click on the Save and continue button to proceed to the next step, as shown in the following image:
Our next step is to choose an installation profile. We can think of this as Drupal's way of preconfiguring items for us that will make our job easier when developing. By default, we can leave the Standard profile selected, but if we choose to configure Drupal ourselves, we can always choose Minimal. Click on the Save and continue button to proceed to the next step, as shown in the following image:
The next screen allows us to review any requirements that Drupal needs or recommends for optimal performance. From here, we can see web server information, PHP version, memory limits, and more:
The requirements review can also alert us to any configuration settings that will allow Drupal to perform better. In our example, we forgot to enable OPcode caching, which allows PHP to compile down to bytecode. Without going into the details of caching, we can easily enable this feature in MAMP PRO.
Begin by opening up the MAMP PRO console and clicking on the PHP tab. Next, we will want to select OPcache from the Cache module to speed up PHP execution dropdown, as shown in the following image:
Click on the Save button and then allow MAMP PRO to restart servers if prompted. Now, we can refresh our Drupal install in the browser, and we will be taken to the next step in the installation process.
Database configuration can sometimes be a tricky part of installing Drupal for the first time. This is generally due to selecting the incorrect database type, wrong database name, or password, or by not specifying the correct host or port number.
The settings we will want to use are as follows:
With these settings, we can click on the Save and continue button to proceed.
If this is successful, we can see the Installing Drupal screen and watch as Drupal installs the various modules and configurations. This process may take a few minutes. If this process fails in any way, please go back and review the previous steps to make sure that they match what we have used.
Before we can wrap up our Drupal 8 installation, we need to configure our site by inputting various settings for site information, site maintenance account, regional settings, and update notifications. Let's proceed now by entering our Site Information.
The site information consists of the following:
Next, we will want to set up the site maintenance account. This is the primary account used to manage Drupal to perform such tasks as updating the core instance, module updates, and any development that needs user 1 permissions.
The site maintenance account information consists of the following:
Regional settings consist of default country and default time zone. These are often neglected and left with their defaults. The defaults are not recommended, as they are important in the development and design of Drupal 8 websites, specifically, when it comes to dates and how they are used to capture data and display dates back to the end user.
For our specific installation, choose the country and time zone for our region.
At last, we have come to our final set of configurations. Update notifications should always be left-checked unless we have no reason to receive security updates to Drupal core or module updates. By default, they should be checked. Click on Save and continue to finalize the configuration and installation of Drupal 8.
Drupal installation is now complete, and we should see the home page of our new website. Say "hello" to Drupal 8.
