Page product tpl php

Templates & layouts

PrestaShop template files are based on the Smarty 4 template engine.

All template files must be stored in the theme’s templates/ subfolder. For instance, the default theme has its template files in the following folder: /themes/classic/templates .

Directory structure

Templates are then split between various subfolders.

/_partials/ Code shared accross the whole site like header, footer or notifications. /catalog/ Product page, product/brand/supplier listing, search result and such. /checkout/ Cart, delivery options, payment options, order confirmations and such. /cms/ All the static content: contact, sitemap, CMS pages and such. /customer/ Everything about the customer’s account and its data. /errors/ All the error templates: not found, server error, forbidden and such. /layouts/ The theme layouts: 1, 2 or more columns, full width, everything is possible.

Template files should be written so that a single .tpl can generate a whole HTML page – unless they are inside a _partials folder or subfolder (see our coding standard, linked from the Prologue chapter of this documentation).

Templates

We make a clear difference between templates and layout.

  • A template extends a layout
  • The layout holds the global organization of the page
  • A template is specific to a feature: the product page for example

There are many templates in a PrestaShop theme, the main ones includes:

  • index.tpl for the home page
  • catalog/product.tpl for the product page
  • catalog/listing/product-list.tpl for any product list page
  • checkout/cart.tpl for the detailed cart
  • checkout/checkout.tpl for the checkout process

Specific templates

If you’re working on a big store in many languages you may need to change the layout of the page depending on the language.

For example you want a different product page for american customers and japanese ones. In this case you simply have to create new template product.tpl and place it in the right folder.

When searching for a template, PrestaShop will check many location to determine which file should be used. It make it very easy to have different template for a given locale or a specific entity id.

Product page example

With the product page, the core will check the following locations (in order) and return the first template found:

Читайте также:  Чтение массива си шарп

graph TD; A(Lookup for template catalog/product with : locale + entity id) A—>B(Lookup for template catalog/product with : entity id); B—>C(Lookup for template catalog/product with : locale); C—>D(Lookup for template catalog/product);

Example for the product with and locale = en-US:

  1. en-US/catalog/product-3.tpl
  2. catalog/product-3.tpl
  3. en-US/catalog/product.tpl
  4. catalog/product.tpl

Category page example

graph TD; A(Lookup for template catalog/listing/category with : locale + entity id) A—>B(Lookup for template catalog/listing/category with : entity id); B—>C(Lookup for template catalog/listing/category with : locale); C—>D(Lookup for template catalog/listing/category); D—>E(Lookup for template catalog/listing/product-list with locale); E—>F(Lookup for template catalog/listing/product-list);

Example for the category with and locale = en-US:

  1. en-US/catalog/listing/category-9.tpl
  2. catalog/listing/category-9.tpl
  3. en-US/catalog/listing/category.tpl
  4. catalog/listing/category.tpl
  5. en-US/catalog/listing/product-list.tpl
  6. catalog/listing/product-list.tpl

This feature is mostly made for developer working on a custom template for a customer.

Layouts

The layout is the organisation of the page: how the parts of your design are arranged.

The typical example is the sidebar: is there a sidebar on your category page or is your product listing taking the whole space?

In PrestaShop, users are given the ability to change the layout of each page independently. As a template developer, it’s your role to ensure your theme is compatible.

Configure layout

What’s in a layout file

The layout is the very top level of the template inheritance tree. Basically it hold the opening and closing tags.

Typical layout files look like the following snippet. This one is a full one:

  $language.iso_code>"> block name='head'> include file='_partials/head.tpl'> /block>  $page.page_name>" >$page.body_classes|classnames>"> hook h='displayAfterBodyOpeningTag'>  block name='header'> include file='_partials/header.tpl'> /block>   block name='breadcrumb'> include file='_partials/breadcrumb.tpl'> /block> block name="left_column"> if $page.page_name == 'product'> hook h='displayLeftColumnProduct'> else> hook h="displayLeftColumn"> /if>  /block> block name="content_wrapper"> block name="content"> 

Hello world! This is HTML5 Boilerplate.

/block> /block>
block name="footer"> include file="_partials/footer.tpl"> /block> hook h='displayBeforeBodyClosingTag'> block name='javascript_bottom'> include file="_partials/javascript.tpl" javascript=$javascript.bottom> /block>

From there, each part of the theme will do its job and replace content inside these bricks, keeping the same organization.

Help and support
Help us make these docs great!

All PrestaShop Developer Documentation are open source. See something that’s wrong or unclear? Submit a pull request.

Источник

Ещё раз о шаблонах

Рано или поздно девелоперу, создающему сайты статусом выше «сайт-визитка», приходится сталкиваться с таким понятием как «шаблоны» или «шаблонизация» визуального представления (не шаблоны проектирования). Что это такое? Механизм шаблонов позволяет отделять визуальное представление веб-приложения (по-скольку работаю только с веб-приложениями, то и рассуждать буду в этом контексте) от бизнес-логики таким образом, чтобы при изменении, например, внутренней логики попутно не приходилось переделывать всю html-верстку. На этом поприще уже давно существует несколько отдельно стоящих флагманских решений, позволяющих создавать довольно гибкие приложения в плане разделения труда дизайнеров-верстальщиков и программистов, а также предотвращать запутанность кода в больших приложениях. Описывать все их нет смысла. Это уже сделано до меня и не один раз. Помимо этого, почти каждая CMS и фрэймворк имеет собственные решения для отделения логики приложения от логики представления.

Конечно, когда речь идет о проекте в десятки тысяч строк кода, когда у заказчика есть возможность нанять и программиста, и верстальщика, то и функционал шаблонов будет только пользой для всех участников проекта. Но когда разработчик в простецкий сайт в 3 страницы начинает втуливать Smarty, это ИМХО уже перебор. В таких случаях я люблю вспоминать выражение Джорджа Шлоснейгла из его замечательной книги «Профессиональное программирование на PHP» – «попытка убить муху молтком».

Действительно, встраивая все тот же Smarty в весьма простой по функционалу сайт, разработчик попросту тратит время. А время, как известно, — деньги. Да и в большинстве случаев заказчику безразлично на каком шаблонизаторе будет работать его сайт. Заказчик больше печется о затраченном времени.

Что же делать, если сайт не «визитка», но и не второй Amazon? Лично я считаю, что в этом случае оптимальное решение проблемы — воспользоваться своей самописной системой шаблонов, весь функционал которой, заточен только для решения узкого круга задач, необходимых для текущего ресурса. Впоследствии вы, возможно, выведите свою «формулу» универсального шаблонизатора с неким минимальным набором функций, расширяемую по мере необходимости в отдельно взятом проекте.

Может показаться, что автор сей статьи весьма скептически относится к Smarty и другим шаблонизаторам. Это не так. Я довольно долго работал с проектом, в котором роль шаблонизатора выполнял все тот же Smarty. И хочу заметить, мне весьма понравилось использование этой системы шаблонов в контексте обширного по функционалу проекта.

  • Возможность назначать переменные шаблону
  • Отдельное пространство имен переменных для отдельно взятого html-шаблона
  • Возможность использования одного шаблона для общего каркаса страницы во избежание повторения конструкций вида require ‘header.tpl’;… require ‘footer.tpl’; в каждом файле
  • Проект является интернет-магазином или социальным сообществом
  • 10-20 типов страниц. Подчеркиваю — НЕ страниц, а типов страниц. Например: страница описания товара. Т.е. html-шаблон для этого типа страниц будет один, но самих страниц, когда каталог заполнится контентом будет много

Рассмотрим простейший класс, который состоит всего из трех методов.

_tmpl = $filename; > public function assign($name, $value) < $this->_vars[$name] = $value; > public function render() < if (count($this->_vars) > 0) < extract($this->_vars); > $tmplPath ; if (file_exists($tmplPath)) < require $tmplPath; >else < throw new Exception("Шаблон _tmpl> не найден"); > > > 

Давайте рассмотрим пример с применением этого класса. Создадим следующую структуру каталогов:

/wwwroot
|
— /classes
| — Template.php
— /templates
| — Main.tpl
| — Catalog.tpl
| — Product.tpl
| — Index.tpl
| — 404.tpl
|— index.php

 

Страница описания продукта №

 

Это главная страница сайта

/** * Буферизация вывода. * Все, что будет выводиться echo-м или print-ом, будет попадать в буфер, а не в браузер пользователю. */ ob_start(); // Подключаем шаблонизатор require dirname(__FILE__).'/classes/Template.php'; // Производим проверку маршрутизации и включаем необходимые шаблоны // Если не один из шаблонов не найден, отправляем клиенту код ошибки и показываем шаблон 404.tpl // Если маршрут не задан, выводим главную страницу if (isset($_GET['route']) && $_GET['route'] == 'catalog') < $tmpl = new Template('Catalog'); $tmpl->assign('ID', $_GET['ID']); $tmpl->render(); > else if ($_GET['route']) && $_GET['route'] == 'product') < $tmpl = new Template('Catalog'); $tmpl->assign('ID', $_GET['ID']); $tmpl->render(); > else if (!isset($_GET['route'])) < $tmpl = new Template('Index'); $tmpl->render(); > else < header("HTTP/1.0 404 Not Found"); $tmpl = new Template('404'); $tmpl->render(); > // Получаем содержимое буфера $content = ob_get_clean(); // Инициализируем шаблон каркаса страницы и выводим ранее сгенерированное содержимое $tmpl = new Template('Main'); $tmpl->assign('content', $content); $tmpl->render(); 

Как видно из примера, содержимое страниц catalog и product изменяется в зависимости от значения $_GET[‘ID’]. Т.о. мы получили два типа шаблонов и неограниченное количество страниц, генерируемых приложением из этих шаблонов.

Вывод: не стремитесь во всех проектах, которыми вы занимаетесь, использовать навороченные библиотеки шаблонизаторов, предоставляющих большое обилие всевозможных инструментов, в большинстве случаев не используемых в должном объеме. Лучше всего написать свое решение, которое поможет сэкономить время, системные ресурсы, а главное — нервы останутся в порядке.

Источник

Оцените статью