- Joomla 3 где формируется head
- Как редактировать title и другие теги секции head в шаблоне Joomla
- Как формируются HTML-заголовки шаблона сайта в Joomla с помощью
- Как вставить автоматические заголовки HTML-документа для блока в Joomla
- HeadRenderer.php — скрипт, отвечающий за формирование заголовка HTML-документа в Joomla
- Creating a basic index file
- Материал из Joomla! Documentation
- Содержание
- Begin
- Body Section
- Module Positions
- Custom Images
- Creating a basic index file
- Материал из Joomla! Documentation
- Содержание
- Begin [ править ]
- Head [ править ]
- Body Section [ править ]
- Module Positions [ править ]
- End [ править ]
- Custom Images [ править ]
- Создание базового индексного файла
- Материал из Joomla! Documentation
- Содержание
- Начнем
- Заголовок
- Тело (Основная часть страницы)
- Module Positions
- Custom Images
Joomla 3 где формируется head
Как редактировать title и другие теги секции head в шаблоне Joomla
Существует 3 способа изменить то, что находится у вас в секции Head:
- Можно отредактировать напрямую функцию fetchHead() в /libraries/joomla/document/html/renderer/head.php (не рекомендуется);
- Воспользоваться методами JDocument и добавить метатеги или теги вставки скриптов;
- Захардкодить теги непосредственно в файле index.php шаблона.
Первым методом пользоваться недальновидно: в случае обновления движка, придется снова править файл head.php
Самый удобный второй способ, который не завязан на файлах ядра и позволяет редактировать секцию заголовка из любого шаблона, компонента или модуля.
Перед тем, как вызывать методы правки заголовочной секции, требуется получить экземпляр текущего документа и присвоить нужные значения до момента отрисовки страницы:
/* Получить объект */
$doc = &JFactory::getDocument();
/* Создает пустой метатег generator. Например, на тот случай, если вы хотите скрыть, что сайт сделан на Joomla. */
$doc->setGenerator();
/* Задает метатег description */
$doc->setDescription();
/* Задает тег title */
$doc->setTitle();
/* Создает пользовательский метатег */
$doc->setMetaData($name,$content);
/* привязывает файл таблицы стилей */
$doc->addStyleSheet(‘/path/to/file’)
/* привязывает файл javascript или скрипта на каком-либо другом языке */
$doc->addScript(‘/path/to/file’)
/* добавляет пользовательский тег. Можно использовать для вставки любого тега в секцию head. */
$doc->addCustomTag();
/* Добавляет кусок кода javascript. Разместит код javascript и обрамит тегом
Как формируются HTML-заголовки шаблона сайта в Joomla с помощью
В Joomla начиная с версии 3.8 HTML-заголовки шаблона сайта, сформированные вызовом получаются в результате работы скрипта HeadRenderer.php , а не /libraries/joomla/document/html/renderer/head.php , как это было до версии 3.8. Поэтому важно понимать, где искать место, в котором происходит ключевых заголовков HTML-документов в шаблоне Joomla. В этой статье рассмотрим то, где эти заголовки формируются и как можно изменить некоторые параметры блока HTML-документа, которые Joomla генерирует на лету.
Как вставить автоматические заголовки HTML-документа для блока в Joomla
Посмотрим ещё раз на простейший файл index.php шаблона сайта по → этой ссылке. Как видно из приведённого листинга, вставка заголовков а также подключение стилей и скриптов в HTML-документ в Joomla осуществляется в этом блоке:
Это происходит путём вызова jdoc с типом head . Этот вызов приведёт к тому, что Joomla автоматически сформирует следующий фрагмент HTML-кода:
Это значительно упрощает задачу создания шаблона для CMS Joomla, но некоторые теги могут оказаться лишними, как и подключение некоторых стилей и скриптов. Поэтому, чтобы разобраться в том, как формируется заголовок HTML-документа в Joomla, нужно знать, каким скриптом он формируется и где этот скрипт находится.
HeadRenderer.php — скрипт, отвечающий за формирование заголовка HTML-документа в Joomla
Как уже стало понятно, в Joomla есть скрипт, отвечающий за формирование заголовка HTML-документа в Joomla и начиная с версии 3.8 он находится тут:
При подключении / отключении дополнительных расширений (модулей и компонентов, а также шаблонов для них), заголовок HTML-документа может удлиняться или укорачиваться в зависимости от того, требуется ли подключение дополнительных файлов со стилями и/или скриптами для его работы и отображения.
Для того, чтобы не передавать лишнюю информацию, можно укоротить список тегов заголовка, например, отключив мета-тег generator, указав в шаблоне:
Это отключит выдачу тега:
То, как это сделать, можно посмотреть на примере по → этой ссылке.
Заберите ссылку на статью к себе, чтобы потом легко её найти: выберите, то, чем пользуетесь чаще всего:
Спасибо за внимание, оставайтесь на связи!
Creating a basic index file
Материал из Joomla! Documentation
The index.php file becomes the core of every page that Joomla! delivers. Essentially, you make a page (like any HTML page) but place PHP code where the content of your site should go. The template works by adding Joomla code into module positions and the component section in your template. Anything added to the template will appear on all pages unless it is added to one of these sections via the Joomla CMS (or customised code).
This page will show the bare-bones code ready for you to cut and paste into your own design.
Содержание
Begin
A Joomla template begins with the following lines:
The first line stops naughty people looking at your coding and getting up to bad things.
The second line is the Document Type Declaration (DOCTYPE), which tells the browser (and web crawlers) which flavor of HTML the page is using. The doctype used above is HTML5, a newer version of HTML that is largely backwards compatible, but contains many new features. You should be aware that this will not work well in Internet Explorer 8 or earlier without a hack. You might want to investigate this situation and your clients’ wishes before deciding on which doctype you want to use. However this is used in Joomla and higher.
The third line begins our HTML document and describes what language the website is in. A html document is divided into two parts, head and body. The head will contain the information about the document and the body will contain the website code which controls the layout.
The first line gets Joomla to put the correct header information in. This includes the page title, meta information as well as system JavaScript. The rest creates links to two system style sheets and to your own style sheet (if it’s named template.css and is located in the css folder of your template directory. So if your template is in http://www.mysite.com/templates/my_template/ then the css files will go in http://www.mysite.com/templates/my_template/css/ ).
Body Section
Amazingly, this will suffice! Yes, it’s a very basic layout, but it will do the job. Everything else will be done by Joomla!. These lines, usually called jdoc statements, tell Joomla to include output from certain parts of the Joomla system. Note: you will need to ensure your menu is set to go into the «top» module position.
Module Positions
Above, the line which says name=»top» adds a module position called top and allows Joomla to place modules into this section of the template. The type=»component» line contains all articles and main content (actually, the component) and is very important. It goes in the centre of the template.
Note: You can add your own module lines anywhere you want in the body, but you have to add a corresponding line to the templateDetails.xml file which sits alongside the index.php of your template.
Finish it off — one last bit:
Custom Images
If you want to add any images to the template you can do so like this:
Here the template variable will fill in the name of your template.
Creating a basic index file
Материал из Joomla! Documentation
The index.php file becomes the core of every page that Joomla! delivers. Essentially, you make a page (like any HTML page) but place PHP code where the content of your site should go. The template works by adding Joomla code into module positions and the component section in your template. Anything added to the template will appear on all pages unless it is added to one of these sections via the Joomla CMS (or customised code).
This page will show the bare-bones code ready for you to copy and paste into your own design.
Содержание
Begin [ править ]
A Joomla template begins with the following lines:
The first line stops people looking at your coding and getting up to bad things.
The second line is the Document Type Declaration (DOCTYPE), which tells the browser (and web crawlers) which flavor of HTML the page is using. The doctype used above is HTML5, a newer version of HTML that is largely backwards compatible, but contains many new features. You should be aware that this will not work well in old browsers without a hack. You might want to investigate this situation and your clients’ wishes before deciding on which doctype you want to use. However, this is used in Joomla and higher.
The third line begins our HTML document and describes which language the website is in. An HTML document is divided into two parts: head and body. The head will contain the information about the document and the body will contain the website code which controls the layout.
Head [ править ]
The first line gets Joomla to put the correct header information in. This includes the page title, meta information as well as system JavaScript. The rest creates links to two system style sheets and to your own style sheet (if it’s named template.css and is located in the css folder of your template directory. So if your template is in https://www.mysite.com/templates/my_template/ then the css files will go in https://www.mysite.com/templates/my_template/css/).
Body Section [ править ]
Amazingly, this will suffice! Yes, it’s a basic layout, but it will do the job. Everything else will be done by Joomla! These lines, usually called jdoc statements, tell Joomla to include output from certain parts of the Joomla system. Note: you will need to ensure your menu is set to go into the «top» module position.
Module Positions [ править ]
Above, the line which says name=»top» adds a module position called top and allows Joomla to place modules into this section of the template. The type=»component» line contains all articles and main content (actually, the component) and is very important. It goes in the centre of the template.
Note: You can add your own module lines anywhere you want in the body, but you have to add a corresponding line to the templateDetails.xml file which sits alongside the index.php of your template.
End [ править ]
Finish it off — one last bit:
Custom Images [ править ]
If you want to add any images to the template you can do so like this:
Here the template variable will fill in the name of your template.
Создание базового индексного файла
Материал из Joomla! Documentation
index.php файл является ядром каждой страницы Joomla!. По сути, вы делаете обычну html-страницу, в которую вставляете PHP код, который будет вставлять содержание вашего сайта. Шаблон создается путем добавления кода в Joomla с указанием позиций модулей и компонентов в соответствующем разделе вашего шаблона. Все, что добавляется в шаблон будет отображаться на всех страницах, кроме разделов сформированных через систему управления сайтами Joomla (или индивидуальным кодом).
На этой странице мы покажем приготовленный базовый код, который Вы можете вырезать и и использовать в вашем дизайне.
Содержание
Начнем
Шаблон Joomla начинается с следующих строк:
Первая строка предотвращает действия злоумышленников, которые хотели бы использовать код вашей страницы в своих целях.
Вторая строка-это Объявление типа документа (DOCTYPE), который сообщает браузеру (и Веб-краулерам) какой тип HTML-кода используется на вашей странице. Тип документа, используемый здесь совместим с HTML5, новой версией HTML, которая во многом сохраняет обратную совместимость, но содержит много новых возможностей. Вы должны знать, что это не будет хорошо работать в Internet Explorer 8 или более ранних без патчей. Вам стоит продумать это и учесть пожелания ваших клиентов, прежде чем решить, какой Тип документа использовать. Так или иначе указанный тип документа является основным в Joomla версии и более поздних.
Третья строка начинает наш HTML-документ и указывет язык сайта. HTML-документ делится на две части, заголовок (head) и тело (body). Заголовок будет содержать информацию о документе, а тело будет содержать код сайта, который управляет макетом.
Заголовок
Первая строка просит Joomla вставить соответствующую заглавную информацию. Это включает в себя Заголовок страницы, Мета-данные, а также код JavaScript. Следующие строки создают ссылки на две страницы стилей и собственную таблицу стилей (если это именованный шаблон.в CSS и находится в папке «CSS», в папке вашего шаблона каталога. Так что если ваш шаблон в http://www.mysite.com/templates/my_template/ тогда CSS-файлы будут идти в http://www.mysite.com/templates/my_template/css/ ).
Тело (Основная часть страницы)
Невероятно, но этого будет вполне достаточно! Да, это очень простой макет, но это будет работать. Все остальное будет сделано на Joomla!. Эти линии, обычно называют декларациями jdoc, которые сообщають Joomla запрос на вставку информации из определенных частей системы Joomla. Внимание: убедитесь, что ваше меню готово быть размещено в «верхней» позиции модуля.
Module Positions
Above, the line which says name=»top» adds a module position called top and allows Joomla to place modules into this section of the template. The type=»component» line contains all articles and main content (actually, the component) and is very important. It goes in the centre of the template.
Note: You can add your own module lines anywhere you want in the body, but you have to add a corresponding line to the templateDetails.xml file which sits alongside the index.php of your template.
Finish it off — one last bit:
Custom Images
If you want to add any images to the template you can do so like this:
Here the template variable will fill in the name of your template.