Php code in template file

What is .tpl file in PHP web design?

TPL is a template file which is a common text file that contains user-defined variables that are entitled to be overridden by user-defined output content when a PHP web application parses the template file. These are used by web applications with server script PHP(but not restricted to) as a template file. Template code is the main content of a .tpl file, which comprises of mainly plain HTML texts tpl language is stored in .tpl files as plain text, so, it’s possible to edit a TPL file with simple text editors.

Situation to use:
While it may seem easy to integrate PHP codes within HTML, it’s not considered a good code management practice as they become difficult for the design team to fairly maintain the files with a mixture of PHP tags and HTML tags. In such a scenario, template codes are used to separate the design from the development. Template files insulate PHP by offering a much simpler tag-based syntax. No PHP knowledge is essential to manage a template file. It is commonly more essential to web designers than PHP developers.

Few common areas where template files are added

  • Re-usability of code where the same design is shared between 3rd parties. Example – An online course portal where colleges make their own page to put their own courses.
  • In Content Management Systems or CMS .
  • A project where web designing team and the PHP development teams are different.

Procedure to use: To use web design with a template with PHP, we will use a framework called Smarty. Smarty is an open-source free framework that comes with simple tag-based template statements to provide clean maintainable presentation codes for a PHP web application.

Steps to get started with Smarty in Apache.

  1. Download the latest Smarty from https://github.com/smarty-php/smarty/archive/master.zip.
  2. Unzip the file and add two folders template_c and cache.
  3. Configure the php.ini file by adding include_path=”.;path to where the libs folder is present in step 3″.
  4. Make a folder in htdocs(root) named smarty and copy the folder configs from the original downloaded folder in step 3.
  5. Add another folder named templates and a PHP file index.php.
  6. Within templates folder add the template file index.tpl
Читайте также:  Html script set cookie

Hence, in templates/index.tpl one can write all his template codes to handle presentations and in index.php all the php codes to handle data processing.

Example: We are demonstrating here a simple example to display data from a PHP file.

  • Output:
  • Advantages of using .tpl file:

    • Flexibility for custom development.
    • Clean code presentation.
    • Fast development or deployment for the programmers and the designers.
    • Quick and easy to maintain.
    • Easy re-usability of code
    • Security: insulation from PHP.

    Practical Application of template files with PHP: A practical example of .tpl file in PHP is the template files used by Phorum. It is a PHP and MySQL-based open source message board system. The .tpl files display data which is dynamically generated by Phorum, such as information on messages, search-related results, and strings of private messages.
    The .tpl files have a specific format of template language which generally comprises HTML and simple Phorum template statements. Four data types are supported by these statements, which may be integers, strings, PHP constants, amd template variables.

    Importance of .tpl file with PHP in Phorum: The Phorum uses .php files if they are placed in the template directory and are named with the appropriate basename besides using TPL files for storing simple template code. A TPL file comprises mainly style data and other information regarding the web pages of the PHP application.

    If Phorum is displaying the header footer template, it first searches for header.php in the template directory and if the file does not exist, will then look for header.tpl. It’s not about just Phorum. Many other parsers and more often custom solutions use .tpl. Also if custom, one can place PHP codes inside the .tpl files too as they are quite robust. OpenCart is a good example of this and vBulletin, where inside the .tpl one can see use PHP codes inside it. That is the reason NGINX and many other servers come pre-built with precautions that prevent people from reading the .tpl files .

    Источник

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

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

    Читайте также:  Css применить ко всем кнопкам

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

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

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

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

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

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

    _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’]. Т.о. мы получили два типа шаблонов и неограниченное количество страниц, генерируемых приложением из этих шаблонов.

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

    Источник

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