search
HomeBackend DevelopmentPHP TutorialCustom layout and template design with Magento

Custom layout and template design with Magento

Sep 01, 2023 am 11:57 AM
template designCustom layoutmagento

In the first part of this series, we learned the basics of Magento module development, including the Magento directory structure, custom module structure, and created a basic "Hello World" module to understand how controllers work in Magento work.

In this article, we will learn how to create block and layout files. Specifically, we will see how layout files and block files work in Magento, and we will learn about the rendering of layout files.

Looking for a quick solution?

If you are looking for a quick solution, there are tons of Magento themes and templates on Envato Market. This is a great way to quickly build a collection of high-quality low-poly items for your project.

Custom layout and template design with Magento

But, let’s continue with the tutorial! First, we will understand what layout files and block files are and how they are useful when rendering front-end pages in Magento, and then we will see how to include them in our custom modules.

What is a layout file?

As the name suggests, layout files are very useful when rendering the home page of Magento. Layout files are XML files located in App > Design > Front End > Interface > Themes > Layout. Here you can see that there are many layout files for any given module. Each Magento module has its own layout file, just like the customer module has customer.xml layout file, The catalog module has catalog.xml layout files, etc. These layout files contain structure blocks and content blocks.

If you’re wondering why Magento requires these blocks, you can learn more in the first part of this series.

Let’s delve into the layout files

Let's take a closer look at layout files through an example. Go to App > Design > Front End > Basics > Layout and open the customer.xml 我> file. Here, all blocks are centered around the main <layout></layout> tag. You can see different <tag></tag> which contain specific blocks.

See the following code snippet:

<!--
New customer registration
-->

    <customer_account_create translate="label">
        <label>Customer Account Registration Form</label>
        <!-- Mage_Customer -->
        <remove name="right"/>
        <remove name="left"/>

        <reference name="root">
            <action method="setTemplate"><template>page/1column.phtml</template></action>
        </reference>
        <reference name="content">
            <block type="customer/form_register" name="customer_form_register" template="customer/form/register.phtml">
                <block type="page/html_wrapper" name="customer.form.register.fields.before" as="form_fields_before" translate="label">
                    <label>Form Fields Before</label>
                </block>
            </block>
        </reference>
    </customer_account_create>

Handle

The handle is the main entity used by Magento to identify the block to be loaded when calling a specific module. <customer_account_create></customer_account_create> is a module-specific handle. This handler is fired when someone opens the customer registration page.

Each nested block handles page-specific content. Some layout files contain <default></default> handles. At this stage, you might ask about the difference between module-specific handles and default handles. In short, a module-specific handle only renders the blocks inside it when the module is rendered in the browser, whereas the default handle loads in most pages.

There are different blocks inside the handle that specify the template file to be rendered when the block is called. There are two types of blocks:

  1. Building Blocks
  2. Content block

In the layout file, we only define content blocks and then wrap them in structure blocks . For example, if someone is calling the customer registration page and we want it to load on the left, right, content, or footer, we will wrap that block in its respective structure block. Here we have wrapped two blocks inside a "content" block, which is a structural block.

The block contains the following attributes:

  1. type defines the block class in which we can define different functions
  2. NameDefinition A unique name for a specific block so that other blocks can refer to the existing block by name and extend it
  3. before/after are properties we can set, allowing us to define the position of the block within the structure block
  4. TemplateDefines the actual phtml file name and path where the HTML and PHP code resides
  5. actionAllows us to use this attribute to trigger any action, such as loading JavaScript, etc.
  6. as is an attribute, mainly used for structure blocks

<reference></reference> tag is used to extend an already existing block. In this example, we extend the content block and insert our own block into it. You must use the correct block name to expand.

<remove></remove> tag is used to delete specific blocks. For example, let's say you don't want to display the right and left columns on your account registration page. In this case, you can simply delete the block using the following syntax: <remove name="your block name">.</remove>

son

When you wrap a block under another block, the wrapped block is called a subblock. Whenever our module calls the parent block, the child block is automatically called.

<block type='core/template' name='parent' template='parent.phtml'>
<block type='core/template' name='child' template='child.phtml'/>
</block>

You can also call the child block individually using the following syntax in the template file echo $this->getChildHtml('child');

打开page.xml 布局文件,你会发现<root></root> 块看起来像下面这样

 <block type="page/html" name="root" output="toHtml" template="page/3columns.phtml">

Magento 从根块开始渲染。所有其他块都是根块的子块。根块定义页面的结构。在这里,您可以看到当前它设置为 3columns.phtml,您可以将其更改为 1column.phtml2columns-right.phtml2columns-left.phtml.

将 CSS 和 JavaScript 添加到布局 XML

对于任何特定页面,您可以将 CSS 和 JavaScript 文件添加到布局标记中,如下所示:

<customer_account_create>
 <reference name='head'>
  <action method="addCss"><stylesheet>css/styles.css</stylesheet></action>
  <action method="addJs"><script>varien/js.js</script></action>
 </reference>
</customer_account_create>

在这里您可以看到我们在客户帐户页面的 head 中添加了一个 CSS 文件和一个 JavaScript 文件。

什么是块类?

块类用于定义特定于特定块的功能。块类文件位于应用程序>代码>本地/社区/核心>您的模块命名空间>您的模块名称>块目录中。这些文件包含我们可以直接与 $this 块特定模板文件中的关键字。让我们通过一个例子来了解块类。

转到位于 app > design > frontend > base > default > layout 目录中的 review.xml 文件,并找到以下代码行:

<!--
Customer account home dashboard layout
-->

    <customer_account_index>

        <!-- Mage_Review -->
        <reference name="customer_account_dashboard">
            <block type="review/customer_recent" name="customer_account_dashboard_info1" as="info1" template="review/customer/recent.phtml"/>
        </reference>

</customer_account_index>

在这里您可以看到引用模板 review/customer_recent  的块 review/customer_recent ">最近.phtml转到应用 > 设计 > 前端 > 基础 > 默认 > 模板 > 审核 > 客户 并打开 最近的.phtml

在此文件中,您可以看到使用 $this 关键字调用两个函数。它们是 $this->getCollection()$this->count()这些函数在其块类文件 recent.php  中定义,该文件位于 应用 > 代码 > 核心 > Mage > 审查 > 阻止 > 客户 目录。

这里,块 type = "review/customer_recent" 指的是在 recent. 文件中定义的 Mage_Review_Block_Customer_Recent 块类。无论您在此类中定义什么函数,都可以直接在相应的模板文件中使用 $this 来使用它。

创建自定义模块布局和块文件

最后,我们留下了带有控制器的自定义“Hello World”模块。在这里,我们创建了自定义模块的布局文件。所以让我们创建它。

要创建布局文件,我们需要首先创建块类文件。在添加类文件之前,我们需要告诉模块我们正在包含块文件。因此,转到 app > code > local > Chiragdodia > Mymodule > etc > config.xml  并添加以下内容代码行:

<frontend>
<layout>
        <updates>
            <mymodule>
                <file>mymodule.xml</file> <!-- Our layout file name-->
            </mymodule>
        </updates>
</layout>
</frontend>
<global>
        <blocks>
            <mymodule>
                <class>Chiragdodia_Mymodule_Block</class>
            </mymodule>
        </blocks>
</global>

最终的 XML 文件包含以下代码行:

<?xml version="1.0"?>
<config>
    <modules>
        <Chiragdodia_Mymodule>
            <version>0.1.0</version>    <!-- Version of module -->
        </Chiragdodia_Mymodule>
    </modules>
    <frontend>
        <routers>
            <mymodule>
                <use>standard</use>
                <args>
                    <module>Chiragdodia_Mymodule</module>
                    <frontName>mymodule</frontName>
                </args>
            </mymodule>
        </routers>
         <layout>
            <updates>
                <mymodule>
                    <file>mymodule.xml</file> <!-- Our layout file name-->
                </mymodule>
            </updates>
         </layout>
    </frontend>
    <global>
        <blocks>
            <mymodule>
                <class>Chiragdodia_Mymodule_Block</class>
            </mymodule>
        </blocks>
    </global>
</config>

创建块类文件

接下来,转到 app > code > local > Chiragdodia > Mymodule > Block 并创建文件 Mymodule.php 包含以下代码行

<?php
class Chiragdodia_Mymodule_Block_Mymodule extends Mage_Core_Block_Template
{
    public function myfunction()
    {
        return "Hello tuts+ world";
    }
}

这里我们声明了类 Chiragdodia_Mymodule_Block_Mymodule ,其中包含函数 myfunction ,我们可以直接从布局模板文件中调用它。

创建布局 XML 文件

转到app > design > frontend > default > default > layout 并创建 mymodule.xml 文件,其中包含以下代码行

<?xml version="1.0"?>
<layout version="0.1.0">
    <mymodule_index_index>
        <reference name="content">
            <block type="mymodule/mymodule" name="mymodule" template="mymodule/mymodule.phtml" />
        </reference>
    </mymodule_index_index>
</layout>

创建模板文件

转到应用 > 设计 > 前端 > 默认 > 默认 > 模板 并创建 mymodule.phtml 文件。在此文件中,我们将调用我们在块类中声明的函数 myfunction

<?php
    echo $this->myfunction();
?>

如果到目前为止一切都正确,您将通过访问 URL yoursite.com/index.php/mymodule/index 看到具有三列布局的输出。

在某些 Magento 版本中,默认主题不包含布局和模板目录。在这种情况下,您可以在app > design > frontend > base 目录中创建布局和模板文件。

这就是 Magento 中布局的工作原理。在上一篇文章中,我们创建了简单的“Hello World”模块,在本文中我们使用布局文件创建它。 Magento 的布局结构一开始有点难以理解,但是一旦你开始修改它,你就会很容易地理解它背后的想法。

In this post I have attached a demo file of the module we have created so far. If you have any questions about this particular issue, please feel free to leave a comment with any questions.

The above is the detailed content of Custom layout and template design with Magento. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.