Adding blocks to the head section in Magento 2

As we all know, the page’s HTML <head> section contains different meta tags, CSS and JS files definition, pieces of JS code etc. As a rule, we don’t need any complex logic to add some proper content there. However, let’s imagine the situation when we need to insert some element that depends on the system configuration or so into the head section.

Magento 2 directives

Have you ever edited a CMS page? Perhaps you’ve inserted a custom image or just added a link to another page of your store. What did you do for that? We assume that you simply copy-pasted the link from your browser and inserted it to the CMS page directly. Then, you have edited one more CMS page or block in the same way. It looks like a good solution. However, imagine that one day you will need a solution for changing, let’s say, a domain name of your store. You will need to fix the old domain name in each of the edited CMS pages and blocks to prevent redirect to it. This is not good approach and, to improve that process, we should use directives.

Redirects is a widely used approach not only in Magento but in most of other web applications. Saying “redirect” we usually mean a rule or a set of rules for sending user from one URL to another. Using Magento 1 you can easily handle redirects by writing just one line of the code, but in Magento 2, because of its new architecture based on Dependency injection, the process of building a redirect is a bit more complex. Let’s review a new redirect creation by building a simple extension that redirects user from a category page to a product view page if there’s only one product in this category.