Drupal

OpenSense Labs: Creating your own Twig Extension in Drupal

Planet Drupal - 5 January 2020 - 11:07pm
Creating your own Twig Extension in Drupal Anmol Mon, 01/06/2020 - 12:37

The templating engine of Drupal 8 has seen a massive turnaround. Unlike Drupal 7, there’s Twig in Drupal 8 instead of PHPTemplate. Twig is basically a templating language for PHP i.e a tool used to output variables inside HTML. Fabien Potencier, the creator of the Symfony framework, gave life to Twig. Contrary to Drupal 7, you cannot call the regular PHP functions in your templates in Drupal 8. he way forward, in Drupal 8, is to create filters and functions.


Twig extension gives more flexibility to process nearly anything inside the twig. Twig can be extended in many ways such as tags, filters, operators, global variables, and functions.

One of the major plus points of creating a twig extension in Drupal 8 is in the view.

Drupal 8 views can often be more challenging in the case where you want to perform operations on the value or need to process the content in the field. When you need to write code often, try to reuse it rather than writing it from scratch every time.

You must use a filter when you want to transform the data you want to display. Imagine you have a title that you always want to be capitalized. For example, twig has the capitalize filter that allows you to transform any text into its equivalent in uppercase.

I came across Twig Extension during one of my E-commerce projects where I had to print dynamic currency name. Drupal Commerce allows only 3 characters long currency code and they have also implemented their own Twig Extension to convert Price object into equivalent price format. So to handle this case where I have to show currency name with more number of characters, I had implemented my own Twig Extension. Similarly, there are several other cases where these Twig Extension can be very handful.

Let’s see an example where we will create a filter that will allow us to count the number of words in the article. The process of creating filters and functions is exactly the same as normal Twig. Also, you can use word count to display the reading time of the article or any other use case as per the requirement.

The main difference between regular Twig and Drupal 8 Twig is that, in Drupal 8, you must create a service definition of the class you are creating and the class must also belong to a namespace, otherwise it will not be registered as a Twig filter in the Drupal environment.

This example assumes you have a module called:

twig_word_count_extension


This will be the basic definition of the inn service.

twig_word_count_extension.services.yml services: twig_word_count_extension.twig_extension: class: Drupal\twig_word_count_extension\TwigExtension\TwigWordCountExtension tags: - { name: twig.extension }


The key tags are also absolutely necessary and that is what Drupal tells you what this class is supposed to do (that is, register it as an extension of Twig).

And now the source code that should be placed in the path defined in the class service definition key.

<?php namespace Drupal\twig_word_count_extension\TwigExtension; use Twig_Extension; use Twig_SimpleFilter; class TwigWordCountExtension extends \Twig_Extension { /** * This is the same name we used on the services.yml file */ public function getName() { return 'twig_word_count_extension.twig_extension'; } // Basic definition of the filter. You can have multiple filters of course. public function getFilters() { return [ new Twig_SimpleFilter('word_count', [$this, 'wordCountFilter']), ]; } // The actual implementation of the filter. public function wordCountFilter($context) { if(is_string($context)) { $context = str_word_count($context); } return $context; } }


Clear your caches and now, if everything goes according to plan, you can use the filter in your templates.

{{ "shuffle me!" | word_count }} {# Return 2. #}


Note: If these twig extensions don’t have other service dependencies (i.e. if you don't inject services in them), the performance is not affected. However, if these extensions have lots of complex dependencies, for example, say those making database connections or perform heavy operations, the performance loss can be significant.

To avail help from our experts for your Drupal projects, you can check out our suite of services. You can also talk to us at hello@opensenselabs.com.

blog banner blog image Twig Symfony Drupal Drupal 8 Blog Type Tech Is it a good read ? On
Categories: Drupal

hussainweb.me: An easier way to get the current node in a block plugin in Drupal 8

Planet Drupal - 5 January 2020 - 1:42pm
It is over a year since I wrote how to get the current node in a block plugin and promised to write a follow-up post with an easier method. Well, better late than never, here it is! The previous method works, so why bother with another method? In short, it’s less code and less code is easier to maintain. Also, instead of doing all the work to get the node and set the correct cache contexts/tags, it is better to let Drupal handle that for us.
Categories: Drupal

Event Scheduler

New Drupal Modules - 5 January 2020 - 5:13am

This module allows specific (code) events to be delayed until the end of page execution, or even until a scheduled time in the future.

This module has nothing to do with calendar or real-world events. It's a code thing only.

THIS CODE DOES NOTHING ON ITS OWN. IT SHOULD NOT BE ADDED UNLESS ANOTHER MODULE NEEDS IT.

The Problem with Events

System events are executed at the time they are issued. This means that non-critical actions might be executed during the page build and therefore delay it.

Categories: Drupal

Video Embed Field Plyr

New Drupal Modules - 5 January 2020 - 3:32am

This module adds a field formatter for the video_embed_field that utilizes the Plyr Video player.

Plyr is a lightweight very extensible HTML5 video player,with out of the box support for Vimeo, YouTube and locally hosted MP4 files.

Categories: Drupal

Enhanced Promotion

New Drupal Modules - 5 January 2020 - 12:40am
Categories: Drupal

Charts Highcharts

New Drupal Modules - 3 January 2020 - 8:51pm

This module is for use with the Charts module, version 8.x-4.x and above. It allows user to integrate with the popular Highcharts library.

Categories: Drupal

Web finger

New Drupal Modules - 3 January 2020 - 6:05pm

Enables WebFinger (RFC 7033) support.

About Webfinger (from the RFC):

WebFinger is used to discover information about people or other entities on the Internet that are identified by a URI using standard Hypertext Transfer Protocol (HTTP) methods over a secure transport. A WebFinger resource returns a JavaScript Object Notation (JSON) object describing the entity that is queried. The JSON object is referred to as the JSON Resource Descriptor (JRD).

Categories: Drupal

JSON:API Page Limit

New Drupal Modules - 3 January 2020 - 9:19am

Customize the page limit for JSON API responses for specific paths.

To use, define a set of paths and values as a service parameter in a custom services.yml file. See the services.yml file in this module for details.

Then make a JSONAPI request to your specified path with page['limit']=250 or whatever higher limit you want.

Note that this module is not tested alongside actual pagination of these high-limit requests. The initial use case is needing all items in one request.

Categories: Drupal

OSTraining: How To Manage Image Styles for Media in Drupal 8

Planet Drupal - 3 January 2020 - 7:46am

For years, Drupal site builders have endured a less than great experience with any media they wanted to use.  It was difficult to manage and reuse images; let alone video, audio, and other media.  A number of excellent contributed modules tried to bridge that gap in Drupal 7; however Drupal 8 committed to having a media manager in core.  

As of December 2019, that wait is over with the Media module now officially out of "experimental" and fully integrated into Drupal core.

Categories: Drupal

Simple Iubenda

New Drupal Modules - 3 January 2020 - 1:40am

A simple integration with the Iubenda (https://www.iubenda.com/) system.

This module provides a simple way of integrating the Iubenda service into your Drupal website.

Once configured, the cookie solution configured on Iubenda will be shown on all pages on your Drupal site, to all visitors to your site. Where possible it'll use the settings from the Iubenda configuration, rather than overriding through the Drupal interface.

Similar modules

Categories: Drupal

joshics.in blog: Drupal 8: Update to 8.8 in five minutes

Planet Drupal - 3 January 2020 - 1:34am
Drupal 8: Update to 8.8 in five minutes bhavinhjoshi 03/01/2020 03/01/2020

Finally, we are one more step closer to Drupal 9. In order to make your Drupal 8 website ready for Drupal 9, you will need to update your existing website to Drupal 8.8, the latest stable release in 8.8.x branch. This branch removes all the incompatible APIs and prepares your website for Drupal 9. And which is why, It is highly recommended that you update to 8.8.

Before you start with the update, make sure you take backup of your website (code base & DB) or preferably, carry out this process on a staging site or on your local Drupal 8 set up. For this, it is assumed that you have composer installed for your Drupal 8 environment.

Modify compser.json

 

The first step is to modify composer.json manually.
1. Unset / empty “replace”: {},
2. Remove "merge-plugin" entirely.
3. Append

“App\\”: “app/”,
“”: ”src/”

to “autoload”

Once you are done with modifying the composer.json, it is time to execute a few commands with composer on CLI.

Execute composer commands


composer remove webflo/drupal-core-strict --no-update
composer remove drupal/core --no-update
composer require 'composer/installers:^1.7' --no-update
rm composer.lock
rm -rf core
rm -rf vendor
composer require drupal/core-recommended:^8.8 --update-with-dependencies

Now, site back and relax while composer performs the update.
Once the updates are downloaded, it is time to perform the db updates using drush updb.

Congratulations! You have successfully updated your existing Drupal 8 website to 8.8 and you are now ready for Drupal 9!

Drupal Drupal 8 Drupal 9 Drupal Planet Get Updates I agree to the privacy policy Email Address CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Categories: Drupal

Save & Continue

New Drupal Modules - 2 January 2020 - 10:42pm
Categories: Drupal

OpenSense Labs: ‘Terraform’-ing with Drupal

Planet Drupal - 2 January 2020 - 9:53pm
‘Terraform’-ing with Drupal Shankar Fri, 01/03/2020 - 11:23

If you look up the word ‘terraform’ in the Oxford English Dictionary, the meaning that you find may make you reminisce about some of the science fiction movies or TV series you have watched or heard of. And you may start wondering if something like ‘terraforming’ is actually possible. Transformation of another planet to make it Earth-like, which is what terraform means, would seem like a glorious idea. As there’s always a ‘but’ associated with any brilliant thought that we have, this terraforming of Mars or any other planet is not possible with the current technologies, says NASA.


Anyway, on Earth, terraforming is possible. (Although this is in no way referring to the tackling of climate change, it would be nice to see some strong measures being taken). Earth, our home, is witnessing a wave of digitisation all around in this 21st century. Amongst different digital innovations that are happening, one of the open-source tools, which is incidentally, and rightfully, named Terraform, is here to metamorphose the web arena. And Drupal web application infrastructure can reap the benefits of Terraform to a great extent.

Infrastructure As Code with Terraform


To better understand Terraform, let’s start with an example where you are hosting a Drupal site on AWS. Managing the infrastructure here is a crucial aspect. You will be required to create an Amazon Elastic Compute Cloud (EC2) instance with your Drupal code to serve traffic. But that’s not all. There are more things to be taken care of. You are required to look after the identity and access management (IAM), subnets, auto-scaling groups, virtual private cloud, security groups, target groups, load balancers, Elastic load balancing and many more. Infrastructure as Code (IaC) is your solution to manage infrastructure resources effectively.

IaC automates the provisioning of infrastructure and allows your digital firm to build, deploy and scale cloud applications rapidly, cost-effectively and with minimum risks. It utilises top-of-the-line descriptive coding language for automating the process of provisioning of IT infrastructure. This reduces the need for developers to manually provision and manage servers, operating systems, database connections, storage and several other infrastructure elements. To apply IaC, leveraging Terraform is your best bet.

What is Terraform anyway? It’s a configuration orchestration tool that can work with private cloud, public cloud or on-premise system and has the provision for secure and convenient design, governance and improvement for infrastructure as code. As a cross-platform, extensible tool, Terraform codifies APIs into declarative configuration files. These can, then, be shared amongst team members, treated as code, edited, analysed and versioned.

“Terraform is a tool for building, changing, and versioning infrastructure safely and efficiently.” - Terraform.io

Terraform enables you to define infrastructure in config/code and lets you rebuild/change and track alterations to infrastructure easily. Terraform’s speed and operations are impeccable. Its plan command ensures that you make alterations to the infrastructure predictably and safely. That is, you will know what Terraform will do before you make any changes which leaves zero possibilities of any sort of surprises later on. By building a graph of all your resources and parallelizing the building and modification of any non-dependent resources, it gives insights into dependencies in the infrastructure. And, intricate changesets can be applied to the infrastructure with the help of minimal human interaction. Being open-source, it also has a lively community for you to easily engage with them and start using it.

Comparison of Terraform with similar tools | Source: IBM

IBM states that, in general, Ansible, Puppet, SaltStack and Chef are considered to be the configuration management tools where the software is installed and managed on existing server instances. Terraform, on the other hand, is considered to be an orchestrator which provides server instances itself thereby leaving the job of configuring those servers to other tools.


Even though Ansible leads the adoption charts, it’s the Terraform that has witnessed a surge in users in recent times. According to a 2019 State of the Cloud survey, conducted by RightScale, Terraform displayed the strongest growth. It expanded from 20% in 2018 to 31% in 2019.

Implementing serverless architecture with Terraform and Drupal

A session at Decoupled Days 2019 showed how Terraform can be used in the Drupal web application infrastructure. It demonstrated how to architect a serverless solution for serving the frontend with data that is fetched via an API from Drupal. The serverless frontend application was hosted with multiple cloud providers available via a CDN (Content Delivery Network). Such an application could be provisioned several times in multiple regions of more than one cloud providers with the help of Terraform. Writing wrapper scripts for Terraform streamlined the process of deploying infrastructure.

Drupal’s multisite capabilities, where multiple separate websites from a single codebase could be run, made the hosting requirements for the backend simple. The Frontend part wasn’t easy as it required to run multiple instances to emulate the number of web properties. All the websites were built on a common stack and the infrastructure resources could be easily shared where needed.

Drupal’s multisite capabilities, where multiple separate websites from a single codebase could be run, made the hosting requirements for the backend simple.

In this decoupled Drupal setup, the infrastructure for static web assets (comprising HTML, CSS, JavaScript, fonts and others) required Amazon S3 or similar storage and a CDN distribution with origin set to the S3 bucket. The frontend code was done using Angular.

With the presence of different environments and the need for an endpoint to access the API, hardcoding the URL during the build time was necessary. IP whitelist was used for Drupal server for high-level security. All the content was retrieved from a proxy. The proxy could be placed behind a CDN thereby improving performance and availability.

With several websites and environments, infrastructure automation was needed. Terraform made it all possible. It enabled the process of writing similar scripts for AWS and Aliyun, for instance. Terraform modules were run once to prepare the environment and create IDs of all the resources. The IDs were set in a configuration file which was accessible to all the Jenkins runs. This made sure that the front end code could be deployed from the CI (Continuous Integration) builds. Terraform also helped in administering the state of all the infrastructure.

Conclusion

System administrators and DevOps engineers strive to do more with less. Defining infrastructure in code and automating its deployment brings about operational efficacy and lower administrative overhead. Terraform is all set to be your go-to toolset for infrastructure automation. And, it can be a great asset in Drupal web application infrastructure.

Using Terraform can be fun. For starters, you can take Terraform for a spin and simply play with it to better understand its efficiency for your digital business.

Offering fantastic digital experience has always been the objective of OpenSense Labs. Talk to our experts at hello@opensenselabs.com and understand more about Terraform’s capability in transforming the landscape of your web application infrastructure.

blog banner blog image Terraform Drupal Drupal 8 Infrastructure as Code Web Application Infrastructure Ansible Chef Puppet SaltStack Serverless Decoupled Drupal Blog Type Articles Is it a good read ? On
Categories: Drupal

Clear tag cache

New Drupal Modules - 2 January 2020 - 9:15pm

####################
## Overview
####################

INTRODUCTION
------------
What?

A cache tag is a string.

Cache tags are passed around in sets (order doesn't matter) of strings, so they are typehinted to string[]. They're sets because a single cache item can depend on (be invalidated by) many cache tags.
Syntax

By convention, they are of the form thing:identifier — and when there's no concept of multiple instances of a thing, it is of the form thing. The only rule is that it cannot contain spaces.

Categories: Drupal

Symphony Blog: Remove /web part from a Composer based Drupal site

Planet Drupal - 2 January 2020 - 8:22pm

Ok, the problem is clear:

  • Your composer based Drupal site put code base to the /web folder
  • You are using a shared hosting which maps your primary domain to /public_html, and you can't change that

Now your users will have to browse your site as http://example.com/web . And it is not cool.

So how to serve your site from the subfolder /public_html/web but removing the /web suffix so it becomes transparent to users?

read more

Categories: Drupal

webform cpf

New Drupal Modules - 2 January 2020 - 4:29pm
Categories: Drupal

Lullabot: Emailing Users About Content Activity in Drupal 8

Planet Drupal - 2 January 2020 - 12:16pm

Site owners and administrators often want to send email to users telling them about content creation or changes. This sounds basic, but there are lots of questions. What exactly needs to be accomplished? Some examples could include:

Categories: Drupal

Kris Vanderwater: Product Development: Acquia ContentHub 2.x

Planet Drupal - 2 January 2020 - 10:48am
Product Development: Acquia ContentHub 2.x Kris Vanderwater 2 January 2020

So my blog's been offline for a while now. I think there was a security issue sometime around 8.2.2 because I just upgraded the public version of the site from 8.2.1 directly to 8.8.1. I actually did an upgrade to 8.8.0 alpha-something that I used to bootstrap the upgrade to 8.8.1, but public-facing the site made a pretty big jump. Some of this is due to laziness on my part, but a pretty significant portion of my disappearance has been due to a new (to this blog) position within Acquia.

Categories: Drupal

Bounteous.com: Things to Look Forward to for Drupalists in 2020

Planet Drupal - 2 January 2020 - 8:12am
An overview and exploration of some of the exciting releases, new features, products, and updates coming in 2020 for Drupal and Acquia.
Categories: Drupal

Pages

Subscribe to As If Productions aggregator - Drupal