Twig lower filter

 The lower filter converts a value to lowercase.

{{ 'WELCOME'|lower }}

{# outputs 'welcome' #}

Twig keys filter

 The keys filter returns the keys of an array. It is useful when you want to iterate over the keys of an array.

{% set sizes = [34, 36, 38, 40, 42] %}

{% for key in sizes|keys %}

    {{ key }}

{% endfor %}


Output

0

1

2

3

4


Twig first filter

 The first filter returns the first "element" of a sequence, a mapping, or a string:

{{ [1, 2, 3, 4]|first }}

{# outputs 1 #}


{{ { a: 1, b: 2, c: 3, d: 4 }|first }}

{# outputs 1 #}


{{ '1234'|first }}

{# outputs 1 #}

Twig upper filter

 The upper filter converts a value to uppercase:

{{ 'welcome'|upper }}

{# outputs 'WELCOME' #}

Twig trim filter

 The trim filter strips whitespace (or other characters) from the beginning and end of a string.

{{ '  I like Twig.  '|trim }}

{# outputs 'I like Twig.' #}

{{ '  I like Twig.'|trim('.') }}

{# outputs '  I like Twig' #}

{{ '  I like Twig.  '|trim(side='left') }}

{# outputs 'I like Twig.  ' #}

{{ '  I like Twig.  '|trim(' ', 'right') }}

{# outputs '  I like Twig.' #}

Arguments

character_mask: The characters to strip

side: The default is to strip from the left and the right (`both`) sides, but `left` and `right` will strip from either the left side or right side only

Twig title filter

 The title filter returns a titlecased version of the value. Words will start with uppercase letters, all remaining characters are lowercase:

{{ 'my first car'|title }}

{# outputs 'My First Car' #}

Twig date_modify filter

 The date_modify filter modifies a date with a given modifier string:

{{ post.published_at|date_modify("+1 day")|date("m/d/Y") }}

The date_modify filter accepts strings (it must be in a format supported by the strtotime function) or DateTime instances. You can combine it with the date filter for formatting.


Arguments

modifier: The modifier

Twig date filter

 The date filter formats a date to a given format.

{{ post.published_at|date("m/d/Y") }}

The format specifier is the same as supported by date, except when the filtered data is of type DateInterval, when the format must conform to DateInterval::format instead.

The date filter accepts strings (it must be in a format supported by the strtotime function), DateTime instances, or DateInterval instances. For instance, to display the current date, filter the word "now".

{{ "now"|date("m/d/Y") }}

To escape words and characters in the date format use \\ in front of each character.

{{ post.published_at|date("F jS \\a\\t g:ia") }}

If the value passed to the date filter is null, it will return the current date by default. If an empty string is desired instead of the current date, use a ternary operator:

{{ post.published_at is empty ? "" : post.published_at|date("m/d/Y") }}

If no format is provided, Twig will use the default one: F j, Y H:i. This default can be changed by calling the setDateFormat() method on the core extension instance. The first argument is the default format for dates and the second one is the default format for date intervals.

$twig = new \Twig\Environment($loader);

$twig->getExtension(\Twig\Extension\CoreExtension::class)->setDateFormat('d/m/Y', '%d days');

Timezone

By default, the date is displayed by applying the default timezone (the one specified in php.ini or declared in Twig -- see below), but you can override it by explicitly specifying a timezone:

{{ post.published_at|date("m/d/Y", "Europe/Paris") }}

If the date is already a DateTime object, and if you want to keep its current timezone, pass false as the timezone value:

{{ post.published_at|date("m/d/Y", false) }}

The default timezone can also be set globally by calling setTimezone():

$twig = new \Twig\Environment($loader);

$twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone('Europe/Paris');

Arguments

format: The date format

timezone: The date timezone

Twig convert_encoding filter

 The convert_encoding filter converts a string from one encoding to another. The first argument is the expected output charset and the second one is the input charset:


{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}

Arguments

to: The output charset

from: The input charset

Twig column filter

 The column filter returns the values from a single column in the input array.


{% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %}


{% set fruits = items|column('fruit') %}


{# fruits now contains ['apple', 'orange'] #}

Twig capitalize filter

 The capitalize filter capitalizes a value. The first character will be uppercase, all others lowercase:


{{ 'my first car'|capitalize }}


{# outputs 'My first car' #}

Twig batch filter

 The batch filter "batches" items by returning a list of lists with the given number of items. A second parameter can be provided and used to fill in missing items:

{% set items = ['a', 'b', 'c', 'd'] %}

<table>

{% for row in items|batch(3, 'No item') %}

    <tr>

        {% for column in row %}

            <td>{{ column }}</td>

        {% endfor %}

    </tr>

{% endfor %}

</table>

The above example will be rendered as.

<table>

    <tr>

        <td>a</td>

        <td>b</td>

        <td>c</td>

    </tr>

    <tr>

        <td>d</td>

        <td>No item</td>

        <td>No item</td>

    </tr>

</table>

Twig abs filter

 The abs filter returns the absolute value.

{% set number = -10 %}

{{ number|abs }}

{# output 10 #}

Twig split filter

 The split filter splits a string by the given delimiter and returns a list of strings.

If you want to split a url , use split filter, suppose you have a url public://Quarterly/2019-07/sample.pdf.

And you want to print only 2019-07 , you can use split filter 

Example 

{% set foo = "public://Quarterly/2019-07/sample.pdf"|split('/') %}

{# foo contains ['public:', '', 'Quarterly' , '2019-07','sample.pdf'] #}

for printing 2019-09  ,  use {{ foo.3 }}

You can also pass a limit argument

A- If limit is positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string;

B- If limit is negative, all components except the last -limit are returned;

C- If limit is zero, then this is treated as 1.


{% set foo = "one,two,three,four,five"|split(',', 3) %}

{# foo contains ['one', 'two', 'three,four,five'] #}

If the delimiter is an empty string, then value will be split by equal chunks. Length is set by the limit argument (one character by default).


{% set foo = "123"|split('') %}

{# foo contains ['1', '2', '3'] #}


{% set bar = "aabbcc"|split('', 2) %}

{# bar contains ['aa', 'bb', 'cc'] #}

Drupal 8 Create custom content type templates - custom page template for particular content type

 Sometimes you need to create a page template for a specific content type so that you can customize it. First enable debug mode, so you can see “File name suggestions” in comments inside your code. 

Drupal allows you to create content types for node templates by the following  naming convention    

node--content-type.html.twig. But things aren’t so simple for page templates. Drupal does not automatically detect page templates for content types purely based on the naming convention. Fortunately it just takes a few lines of code and you can create a page template for any content type you choose.

Page template

To tell Drupal to use the page template for a content type, you can implement hook_theme_suggestions_page_alter(). This hook is used whenever a page.tpl.php template is used and allows you to suggest alternative templates.

In this case, you are going to tell Drupal to use a specific page template for a specific content type, for do that add this code in “.theme” file in you theme.

/**

* Implements bedrupal_suggestions_page_alter().

*/

function example_theme_suggestions_page_alter(array &$suggestions, array $variables) {

if ($node = \Drupal::routeMatch()->getParameter('node')) {

$suggestions[] = 'page__' . $node->bundle();

}

}

Now you can copy the template page.html.twig and paste in “/template/layout/” folder under your custom template, and rename in “page–customposttypename.html.twig”.

Clear cache, reload single custom post type page, and in “inspect” mode, you can see your new page under.

Node teamplate

Now create a folder “node” under “themes/custom/your_theme/template”, that’ll be the folder that contain all your custom post type template files.

Now copy the file “node.html.twig” from “modules/node/templates/” in folder “node” created before and rename in “node–customposttypename.html.twig”.

This is the file that wrap all content.

Enable clean URLs in Drupal

 In Drupal, clean URLs are enabled by default and can't be disabled. However, a rewrite module must be installed on your web server.

Check your browser's address-bar. Your site's URLs should not contain ?q= within the URL.

Example of proper 'Clean URLs'

http://www.example.com/node/83

Example of 'Clean URLs' not working

http://www.example.com/?q=node/83

Server configuration for Clean URLs

Enable mod_rewrite for Apache. You can talk to your web host or consult the Apache documentation for mod_rewrite to get more information on how to do this. At a minimum, this will involve making sure that mod_rewrite is enabled for your installation of Apache.

To test if mod_rewrite is available in Apache2, you can type the following at a command prompt, to list all installed Apache modules:

apache2ctl -M 

On some systems this command may be:

apachectl -M 

Or,

httpd -M 

In the output, check to see if the rewrite_module is included in the list of modules.

If the rewrite module is not in the list, it will have to be either compiled-in or made available as a loadable module. Generally speaking, you can tell Apache to load the module by including

LoadModule rewrite_module modules/mod_rewrite.so

AddModule mod_rewrite.c

in your Apache configuration file (see below for information on the configuration file). Be sure to uncomment AddModule mod_rewrite.c, if it is in your configuration file but has been commented out. The following may work to enable the module without editing any files:

a2enmod rewrite 

Note that these approaches may not work for all combinations of operating system and Apache server -- consult the Apache documentation that came with your Apache software for the correct syntax.

Remember to restart Apache for the new configuration to take effect.

The next step is to locate the appropriate Apache configuration file for your site. Depending on your server configuration, the appropriate Apache configuration file could be httpd.conf, a virtual-host-specific file (vhost.conf), a specific site file (e.g. "default"), or apache2.conf. They are usually located in /etc/httpd/conf, /etc/apache2, or a sub-directory; if not, try the command:

find /etc -name httpd* 

Or,

find /etc -name apache2* 

The next step is to copy or include the Drupal-specific settings directly into your configuration file ( .htaccess file).

RewriteEngine on

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteCond %{REQUEST_URI} !=/favicon.ico

RewriteRule ^ index.php [L]

Or this example on a Debian 8 + Apache2 + ISPConfig, using wildcard to match all sites installed:

<Directory /var/www/clients/*/*/web/>

  RewriteEngine on

  RewriteBase /

  RewriteCond %{REQUEST_FILENAME} !-f

  RewriteCond %{REQUEST_FILENAME} !-d

  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

</Directory> 

Difference between Drupal 7 and Drupal 8

Code Base

Drupal 8 comes integrated with Symfony framework, a high performing PHP framework with improved code security. Symfony will help Drupal developers with the following features.

Multi-lingual

Symfony comes with an in-built component called ‘Translation.’ It handles language files and helps developers manage website content in multiple languages, making it easy to create multilingual websites.

Serializer

This other component publishes the data in various formats from XML or JSOn. With it, Drupal can integrate with various 3rd parties to show data on a website.

Routing

With routing, developers define rules for making page URLs search engine friendly (SEO-friendly URLs). This creates better-ranking websites on search engines.

Object-Oriented Programming

Using object-oriented programming concepts, Symfony implements various properties of OOPS concepts.

On the other hand, Drupal 7 does not have a powerful framework to manage its codebase. Developers still use the Drupal 7 codebase to write functions, but the lack of framework features makes it harder to manage code effectively.

Theme Engine

Drupal 8 comes with a new theme engine –Twig. Twig is a PHP-based theme engine which allows programmers to write templates using a simpler syntax. But the developers can still use Twig to crate templates which are both fast and secure. Hence, the developers can take advantage of the new theme engine provided by Drupal 8 to create beautiful and functional websites according to varying business needs.

Caching and compiling

When your website page renders with Drupal 8, the Twig converts the template into compiled PHP template. After the compilation, the template files are cached for reuse. This allows for faster page access to site visitors.

Docblock

However, within Drupal 7, the developer uses the PHP template to write code with PHP syntax. So then, the docblock is written as:

<?php

/**

* @file

* File description

*/

?>

Within Drupal 8 the docblock is written as:

{

/**

* @file

* File description

*/

#}

Printing a variable

Drupal 7 (PHPTemplate):<div class="content"><?php print $content; ?></div>

Drupal 8 (Twig):<div class="content">{{ content }}</div>

Conditions

Drupal 7 (PHPTemplate):<?php if ($content->comments): endif; ?>

Drupal 8 (Twig): {% if content.comments %} {% endif %}

File and function names

Drupal 7 (PHPTemplate): node--article.tpl.php

Drupal 8 (Twig): node--article.html.twig

Responsive Design

Drupal 7 does not use breakpoint media queries. It has a different approach to manage how the site appears on various screens and devices.

Drupal 8 uses the breakpoint media queries, which saves any extra efforts to make a website responsive on various devices.

Text Editor

The next big difference is the text editor. Drupal 8 improves the editor in a new way. The new editor is named as CKEditor which offers WYSIWYG editing and a robust editor. The availability of WYSIWYG enables end users to have proper editing experience right from the backend.

Core Multilingual

Another aspect of Drupal that got overhauled in the Drupal 8 release is the multilingual feature. Four new modules were integrated into Drupal 8 including the interface translation, configuration translation, language, and content translation. By using these modules, developers can easily use these modules to translate content according to the website’s need.

Website Loading Speed

The current web is all about website speed. If a website doesn’t load within 3 seconds, it gets abandoned by the visitor. With Drupal 8, developers can now develop websites that load faster. It is done by improving caching entities. The method is to ensure that the website doesn’t load assets again if the visitor has visited the page earlier.

Drupal Node

 All content on a Drupal website is stored and treated as "nodes". A node is any piece of individual content, such as a page, poll, article, forum topic, or a blog entry. Comments are not stored as nodes but are always connected to one. Treating all content as nodes allows the flexibility to create new types of content. It also allows you to painlessly apply new features or changes to all content of one type.

The ability to create different "content types" is a way Drupal allows you to have different kinds of nodes for different purposes. For example, an "article" is one content type, a "book page" is another, and a "blog entry" yet another. You can also create new content types of your own.

The Node module manages the creation, editing, deletion, settings, and display of the main site content. Content items managed by the Node module are typically displayed as pages on your site, and include a title, some meta-data (author, creation time, content type, etc.), and optional fields containing text or other data. 

Each node has an unique ID.

Attributes all nodes

Every node in a Drupal site no matter its type will have some common attributes. The following list is not complete, but it includes some of the more important node attributes:


Title: it is always required.

Node ID (nid): This is a numeric identifier that Drupal uses internally to differentiate between nodes. The first one will have Node ID 1 and this number will increment by 1 each time a new node is created. Once set this number is not changed. Deleting a node does not make its nid available for future use.

URL alias: Every node in a Drupal site can be accessed via its Node ID appending /node/[nid] to the domain of the site. Nevertheless, humans are better remembering phrases than numbers. Imagine that someone tells you to read the blog post at /node/491827. Wouldn't it be easier to remember something like /blog/intro-to-drupal-views? In my humble opinion, the latter is easier to remember. That is a URL alias: some text that you can set as an alternative to access a specific node. The URL alias is optional and even if set the node will continue to be available in its canonical /node/[nid] path. Using modules like Pathauto you can define rules for creating URL aliases so you do not have to write them manually each time.

Publication status: this is a 'yes' or 'no' (boolean) value that indicates whether a node is available to the general public or not. You might start creating a blog post, but need to review some resources before making it public. Instead of losing your progress, you can save the node as a draft (not published) making it available only to certain privileged users. Later you can revisit the node and, when it is ready, save it as published making it available to everyone.

Type: this is the content type the node belongs to. For example: basic page, article, car, event, etc.

Author and publication time: Who created the node and when (date and time) it was published. If content revisioning is enabled for the content type then Drupal keeps track of who performed  each modification and when it was made. Content revisioning will be explained in a later blog post.

Menu settings: whether this node should be included in a menu, for example, to appear in the main navigation of the website. Imagine a node containing general information about your organization having an "About Us" link in the main navigation.


How I get the node field value in node.html.twig tpl

If you want to create tpl for a particular content type node use below naming convention

node--content_type_machine_name.html.twig

For Printing Title -  {{node.title.value}}

For Printing Body -  {{node.body.value|raw}}

For Printing Image  - {{ file_url(node.field_image.entity.fileuri) }}

For Printing reference field Value - {{node.field_author.entity.title.value}}
    field_author - entity machine name
    title -  field name that you want to print for reference entity

  suppose you want to print Entity reference image url you can use 
  {{file_url(node.field_author.entity.field_author_image.entity.fileuri)}}

Git how do you revert a commit that has already been pushed and made public

 Remove or fix the bad file in a new commit and then push it to the remote repository. This is the most obvious way to fix an error. Once you have made necessary changes to the file, then commit it to the remote repository using the command: git commit -m “commit message”

Also, you can create a new commit that undoes all changes that were made in the bad commit. To do this use the command

git revert <name of bad commit>

What is Git

 Git is a Distributed Version Control system(DVCS). It lets you track changes made to a file and allows you to revert back to any particular change that you wish.

It is a distributed architecture that provides many advantages over other Version Control Systems (VCS) like SVN. One of the major advantages is that it does not rely on a central server to store all the versions of a project’s files.

Instead, every developer “clones” a copy of a repository I have shown in the diagram with “Local repository” and has the full history of the project available on his hard drive. So when there is a server outage all you need to do to recover is one of your teammate’s local Git repository.

There is a central cloud repository where developers can commit changes and share them with other teammates.

Few Git commands

git rm [file] -  deletes the file from your working directory and stages the deletion.

git log  - list the version history for the current branch.

git show [commit] - shows the metadata and content changes of the specified commit.

git tag [commitID]  - used to give tags to the specified commit.

git checkout [branch name] - used to switch from one branch to another.

git checkout -b [branch name] - creates a new branch and also switches to it.

Create a new branch in Git

 Git makes creating and managing branches very easy. In fact, the power and flexibility of its branching model is one of the biggest advantages of Git!

The "git branch" command is used for a variety of tasks:

creating new local branches

deleting existing local or remote branches

listing local and/or remote branches

listing branches that e.g. haven't been merged yet

create a new branch based on the current HEAD

$ git branch <new-branch>

create a new branch based on some existing one

$ git branch <new-branch> <base-branch>

create a new branch from a specific commit

$ git branch <new-branch> f71ac24d

create a new branch from a specific tag

$ git branch <new-branch> v1.2

create a new branch from a remote branch

$ git branch --track <new-branch> origin/<base-branch>

$ git checkout --track origin/<base-branch>

create a new branch in a remote repository

$ git push -u origin <local-branch>

Advantages of Drupal

 Drupal is not just a CMS. It's CMF (Content Management Framework). CMS is a derivative of CMF, a particular use case implemented by default to help beginners (Article and Simple Page content types, used on most pages).

Over the years, Drupal has become one of the most powerful open source CMS’s and the standard choice for thousands of large web projects. It offers up-to-date digital solutions and is backed by active community members and teams of seasoned developers all over the globe. Such popularity is justified by its flexibility, scalability, and high security. The latest version of Drupal is proof of how far it has come. Drupal 8 & 9 comes with more than 200 new enhancements and great features to meet your business goals.

Advantages of Drupal

There are many reasons why Drupal is the top three most used CMS, and why many small to big complex systems have made it their options. Here are those.

Community

Drupal is an open source CMS. Aside from being a licensing option, open source is really a culture and an approach to technology that revolves around the free exchange of ideas and innovation. The open source community offers extensive public documentation, well-developed discussion boards, chat and mailing lists, alongside an air of approachable online culture.

For every new Drupal release, individuals and organizations around the globe contribute their time and resources to reviewing code, creating documentation, testing and incorporating feedback directly from the users themselves to deliver the best experience possible. 

Flexibility

It’s not a chance that Drupal is considered the most flexible CMS. We have always thought that if you have an idea about any functions, contents, you can certainly create it with Drupal. Seriously. You can create any content on site. You can customize anything to fit your taste. You can create any website type that you want.

Scalability

By scalability, we mean that you can extend your Drupal core to a higher level with a variety of contributed Drupal modules. What’s great with the Drupal modules is that they integrate perfectly well with Drupal core. They also connect absolutely efficiently with the modules. This is regardless of the fact many modules are totally different. It is due to the natural structure & built in system of Drupal. This thereby enhances the power of extending your Drupal website. It is also a core strength of Drupal compared with other CMS. Meanwhile, Drupal is an open source. So suppose the modules you want don’t exist, you can create one, edit an existing module.

Security

The Drupal Security Team is made up of security experts from around the world who are dedicated to analyzing and identifying potential risks in both Drupal core and contributed Drupal modules. Every new contributed model must undergo stringent review by a team of Drupal core maintainers before it is released publicly. Despite the common misconception that open source software is more vulnerable than proprietary models, Drupal’s large, dedicated open source community gives it an advantage by empowering millions of developers to detect issues in the code and submit bug reports.

Mobile capabilities

Recent trends show that the browsing experience through some sort of mobile device is increasing exponentially. Drupal 8 puts mobile users at its core and is built for mobile-first and PC second. It includes a new, fully mobile administrative toolbar with responsive themes. This is extremely helpful for editors to quickly create and edit content, easily make any other changes to it from any mobile device, and build APIs that can be used for mobile apps. You can apply all this by using a handy, purpose-built interface on a small screen. The result is responsive and suitable for any device design.

Multilingual features

The translation was never as easy as it is now. Businesses with a target global audience can benefit from Drupal multilingual capabilities. The translation systems of Drupal 8 have been completely rewritten and are fully integrated into the CMS making it possible to install it in one of 100 languages right out of the box. The latest version is configured with a powerful translation module with content translation, interface translation, and configuration translation to provide an excellent experience across multiple devices. You can easily translate any component of the software (taxonomy, comments, image styles, and more) and even get software translation updates from the community. It saves a large amount of time and money.

Configuration Management

In Drupal 8, it has a new user “Export Configuration” function that helps you export either the full site configuration or a single configuration file. The whole configuration is presented in the form of text files in the YAML format. There is no longer a need to use additional modules (e.g. the Features module) to deploy a configuration from one environment to another.

Web Services

Drupal 8 makes things easier than ever for mobile app developers. Businesses can build high-quality mobile apps by using Drupal 8 as the data source. Furthermore, backend developers are able to leverage Hypertext Application Language (HAL), provide your content in the format of JSON or XML, display views-generated lists as services, and much more.

Fast Theming

Designing beautiful websites with beautiful themes is becoming much easier. Drupal 8 has one more powerful tool called Twig, a template engine that replaces Drupal’s default PHPTemplate engine. Being a part of the Symfony2 framework, Twig provides a greater separation between logic and display (PHP code is no longer embedded in templates). It is fast, flexible, and secure.

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...