In this article, we will be covering the basics of Magento template files. We will go over their introduction and do some basic modifications.
This will include displaying featured products on the homepage and how to load JavaScript in the footer.
Following on from our previous article, we have seen that the layout files control each block in a theme and decide what does and doesn't get displayed. But what gets rendered inside of that block is where the template files come into action.
In this article, we will be focusing on the following directories:
app/design/frontend/<package_name>/<theme_name>/template/
app/design/frontend/<package_name>/<theme_name>/locale/
If you've just joined us please be sure to checkout the previous articles in this series.
For reference, we've covered:
Without further a do, let's get started.
Magento template files are PHTML files made up of a mixture of HTML and PHP, some of which render a page such as 1column.phtml
while others render specific blocks within a page such as header.phtml
.
For the majority of the time during development of a website these are the files we'll mostly be working with, for front end developers, that is. Once the XML is in place and a template gets called, it is expected that the file will be parsed and displayed accordingly.
There are hundreds of template files available, knowing which one to edit and then track down the file in the hierarchy can be tricky when first starting out.
All is well though, there are a few neat admin area settings which can help us out, they will save us hours of headache!
Important to note, we can only use the following settings at the "Website" or "Store View" scope, the settings aren't available to us on the "Default Config" scope, so we must remember to change the scope once logged in. This is useful though as it means we can toggle the settings just for a particular website or store view rather than globally.
These will quickly identify which files are being loaded for a specific page by showing us the path to the file. Toggling it on or off is a quick setting change in the admin area.
Head over to system > configuration. Then in the left hand menu scroll all the way down to the bottom and click "Developer" from under the "Advanced" heading. Once we have changed the scope to "Main Website" we then have the setting available to us under "Debug".
It would appear that nothing has happened once you've clicked save config, but if you go to the front end of the website, the homepage for example, and refresh the page you will see the hints coming through.
With this we now know where the files are located, and if any modifications are required simply copy the file across from base to our theme and modify as necessary.
We can also set "Add Block Name to Hints" to "Yes" if we want further information, this is generally used for back end development so I wouldn't worry about this setting too much.
Now, on to the code. I will run through a couple of modifications which are often used in theme development, but again I will only be touching the surface on whats possible.
Let's get started...
This point has to be the most common request on any website, everyone wants to show off a handful of products on the landing page of their site right?
It's actually much easier than you'd imagine, with a combination of XML and PHP we can achieve this in no time. There are, as with many things in Magento, more than one way of doing this. I'm going to show you what I think is the easiest method.
First up, we need to create our category in the admin area that will hold our products. Once logged in head over to catalog > manage categories. For this example, we will create a subcategory under root, so we need to click on "Root Catalog" and then click on the "Add Subcategory" button. Enter a title for the category, make sure "Is Active" is set to "Yes" and then click "Save Category".
Make a note of the category ID number at the top as we will be needing this later on:
This will be a good time to also add some products to the category we have just created. To do this click on the "Category Products" tab and select the products you want to display, not forgetting to click "Save Category" once we have finished.
Next up, we need to create our template where our foreach
loop will be run.
For this we will base it off the product list template which has all the necessary code already done for us, we just need to make a few adjustments to suit our needs.
app/design/frontend/base/default/catalog/product/list.phtml
Copy to:
app/design/frontend/<package_name>/default/catalog/product/list-home-featured.phtml
We will then make some modifications to our file.
The finished file will look like the following:
<?php /** * Product list template * * @see Mage_Catalog_Block_Product_List */ ?> <?php $_categoryId = 35; $_category = new Mage_Catalog_Model_Category(); $_category->load($_categoryId); $_productCollection = $_category->getProductCollection(); $_productCollection->addAttributeToSelect('*'); ?> <h2><?php echo $_category->getName(); ?></h2> <?php if(!$_productCollection->count()): ?> <p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p> <?php else: ?> <div class="category-products"> <ul class="products-grid"> <?php foreach ($_productCollection as $_product): ?> <li class="item"> <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"> <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /> </a> <h2 class="product-name"> <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"> <?php echo $_product->getName(); ?> </a> </h2> <?php if($_product->getRatingSummary()): ?> <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?> <?php endif; ?> <?php echo $this->getPriceHtml($_product, true) ?> <div class="actions"> <?php if($_product->isSaleable()): ?> <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button> <?php else: ?> <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p> <?php endif; ?> <ul class="add-to-links"> <?php if ($this->helper('wishlist')->isAllow()) : ?> <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li> <?php endif; ?> <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?> <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li> <?php endif; ?> </ul> </div> </li> <?php endforeach ?> </ul> </div> <?php endif; ?>
Don't forget to change the value of the $_categoryId
variable to your category ID.
Lastly we just need to create an XML block that will load in the template we have created above. We will do this in our local.xml
file like so:
<?xml version="1.0"?> <layout version="0.1.0"> <cms_index_index> <reference name="content"> <!-- home featured products --> <block type="catalog/product_list" name="home.featured.products" after="-" template="catalog/product/list-home-featured.phtml" /> </reference> </cms_index_index> </layout>
That's all there is to it, pretty straight forward right? Below is a screenshot of the finished product.
For starters, we would think Magento already has this ability built in through the XML when we add our scripts, some sort of parameter we could pass in, but we would be wrong - Magento isn't going to make it that easy for us!
WordPress, on the other hand, does this perfectly via the wp_register_script
. Maybe a back end developer will pick up on this and add in the ability to pass through an additional XML parameter, now there's a side project for someone to get cracking with.
Any takers?
So, fortunately for now there is an alternative method to getting this to work.
I think it's important to cover this topic as it will improve the speed of our site which everyone wants. I tend to leave Magento core JavaScript files left as they are in the <head>
, I may minify them but apart from that they remain as they are.
Anything we add in on top of Magento, such as jQuery and our own custom functions there is no harm in loading these in the footer. When developing a website I tend to keep a keen eye on the <head>
tag, when a third party module gets installed it usually adds something in here. With a bit of work we can edit the third party module XML and point it to load in the footer - it's well worth the extra five minutes doing so!
First we need to create an XML block in our local.xml
file within the default layout handle like so:
<?xml version="1.0"?> <layout version="0.1.0"> <default> <reference name="root"> <!-- adds ability to load js in the footer --> <block type="page/html_head" name="footer.js" as="footer.js" template="page/html/footer-js.phtml"> <action method="addItem"><type>skin_js</type><name>js/build/jquery.min.js</name></action> </block> </reference> </default> </layout>
Notice we are using the same method of adding JavaScript files as we did in the previous article. If you need a refresher click here, for demonstration purposes we will add in a local copy of jQuery.
Now we can go about creating our template file. Create a new file in:
app/design/frontend/<package_name>/default/page/html/footer-js.phtml
with the following content:
<?php echo $this->getCssJsHtml() ?>
Lastly we need to add a single line of code into our template files just before the closing </body>
tag.
Our template files can be found at app/design/frontend/base/default/page/
not forgetting to copy them over to our own theme. There are multiple template files, I have collated a list together below:
1column.phtml
2columns-left.phtml
2columns-right.phtml
3columns.phtml
Below is an example of how it should look:
... ... <?php echo $this->getAbsoluteFooter() ?> <!-- adds ability to load js in the footer --> <?php echo $this->getChildHtml('footer.js') ?> </body> </html>
With all the steps now complete if we refresh our page and view source we will now see the script being loaded in just before the closing </body>
tag.
If you've made it this far I think a congratulations is in order! There is a lot to take in one sitting but hopefully it's all starting to make sense.
This series is only the tip of the iceberg, Magento is a very powerful platform and has much more to offer than what we have covered. I hope it has given you an insight into the theme principles of Magento and that you can put it to good use.
There's no better way to learn Magento but to just get stuck in, you'll learn the ropes in no time.
As always I'm more than happy to assist if you need a hand with anything. Also be sure to checkout my Magento Boilerplate which has a whole bunch of goodies inside.
Until next time.
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/Hands-on With ARIA: Accessibility Recipes for Web Apps
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Introduction to API Calls With React and Axios
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Site Authentication in Node.js: User Signup
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/Learn to Code With JavaScript: Part 1, The Basics
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…