sprintf
Возвращает строку, созданную с использованием строки формата format .
Строка формата состоит из директив: обычных символов (за исключением % ), которые копируются в результирующую строку, и описатели преобразований, каждый из которых заменяется на один из параметров. Это относится также к printf().
Каждый описатель прреобразований состоит из знака процента ( % ), за которым следует один или более дополнительных элементов (в том порядке, в котором они здесь перечислены):
- Необязательный описатель заполнения, который определяет, какой символ будет использоваться для дополнения результата до необходимой длины. Это может быть пробел или 0 . По умолчанию используется пробел. Альтернативный символ может быть указан с помощью ‘ . См. примеры ниже.
Пример 1. Изменение порядка параметров
Этот код выведет «There are 5 monkeys in the tree». Теперь представьте, что строка формата содержится в отдельном файле, который потом будет переведен на другой язык, и мы переписываем ее в таком виде:
Пример 2. Изменение порядка параметров
Появляется проблема: порядок описателей преобразования не соответствует порядку аргументов. Мы не хотим менять код, и нам нужно указать, какому аргументу соответствует тот или иной описатель преобразования.
Пример 3. Изменение порядка параметров
Нумерация аргументов имеет еще одно применение: она позволят вывести один и тот же аргумент несколько раз без передачи функции дополнительных параметров.
Пример 4. Изменение порядка параметров
Примеры
Пример 5. sprintf(): заполнение нулями
Пример 6. sprintf(): форматирование денежных величин
Пример 7. sprintf(): научная нотация
- Множественное число имен существительных в Joomla 3
- JUser: работа с объектом пользователя
- Работа с изображениями в Joomla (JImage)
- Usergrouplist (usergroup) модальное окно выбора группы пользователей xml
- Поля формы и файлы конфигураций, XML параметры расширений.
- JForm – фильтры полей в формах Joomla
- User модальное окно выбора пользователей
- Imagelist выпадающий список изображений xml
- Работа с файлами в Joomla (Класс JFile)
- Работа с сессиями в Joomla (JSession)
- Как работать с сессиями в Joomla.
- Работа с папками, класс JFolder
- Создание своего типа поля
- 1. Лекция: Архитектура Joomla. Базовые сведения
- JResponseJson – возвращаем данные в формате JSON
- JMail — Отправка почтовых сообщений
- JPagination — постраничная навигация в компоненте
- Описание класса Joomla JFactory
- Обработка пользовательского ввода в Joomla, начиная с 2.5 (JInput)
- Email — поле электронной почты.
JDocument
The «API15» namespace is an archived namespace. This page contains information for a Joomla! version which is no longer supported. It exists only as a historical reference, it will not be improved and its content may be incomplete and/or contain broken links.
JDocument is an abstract class which provides a number of methods and properties appropriate for a range of document types. Some of the methods listed will be overridden by the child class so you should check the child class documentation for further information.
Defined in [ править ]
Methods [ править ]
Method name | Description |
---|---|
__construct | Class constructor |
getInstance | Returns a reference to the global JDocument object, only creating it if it doesn’t already exist. |
setType | Set the document type |
getType | Returns the document type |
getHeadData | Get the document head data |
setHeadData | Set the document head data |
getBuffer | Get the contents of the document buffer |
setBuffer | Set the contents of the document buffer |
getMetaData | Gets a meta tag. |
setMetaData | Sets or alters a meta tag. |
addScript | Adds a linked script to the page |
addScriptDeclaration | Adds a script to the page |
addStyleSheet | Adds a linked stylesheet to the page |
addStyleDeclaration | Adds a stylesheet declaration to the page |
setCharset | Sets the document charset |
getCharset | Returns the document charset encoding. |
setLanguage | Sets the global document language declaration. Default is English (en-gb). |
getLanguage | Returns the document language. |
setDirection | Sets the global document direction declaration. Default is left-to-right (ltr). |
getDirection | Returns the document language. |
setTitle | Sets the title of the document |
getTitle | Return the title of the document. |
setBase | Sets the base URI of the document |
getBase | Return the base URI of the document. |
setDescription | Sets the description of the document |
getDescription | Return the title of the page. |
setLink | Sets the document link |
getLink | Returns the document base url |
setGenerator | Sets the document generator |
getGenerator | Returns the document generator |
setModifiedDate | Sets the document modified date |
getModifiedDate | Returns the document modified date |
setMimeEncoding | Sets the document MIME encoding that is sent to the browser. |
setLineEnd | Sets the line end style to Windows, Mac, Unix or a custom string. |
setTab | Sets the string used to indent HTML |
loadRenderer | Load a renderer |
render | Outputs the document |
Importing [ править ]
jimport( 'joomla.document.document' );
Examples [ править ]
Code Examples [ править ]
Adding support for new document types
New document types are added by creating a new sub-directory under the /libraries/joomla/document/ directory with the same name as the type. For example, to add a document type called «mytype», you would create the directory /libraries/joomla/document/mytype. In this directory you must then create a file called mytype.php which will contain the class definition for JDocumentMytype which extends JDocument. Look at the code for existing document types to see what needs to be done.
Using own library in your extensions
There are several approaches to registering your own library with Joomla’s autoloader and then use it in your extension. All these approaches are based on the JLoader class. For this tutorial, assume that your library is located in the /libraries/mylib folder.
Discovering Classes
Classes in a folder that follow a naming convention can be registered collectively with JLoader’s discover() method. The discover method looks at the file names in a folder and registers classes based on those names. Additional arguments can be used to update the class register and recurse into sub-folders.
// Register all files in the /libraries/mylib folder as classes with a name like: MyLib JLoader::discover('Mylib', JPATH_LIBRARIES . '/mylib');
As you can see this method working by following the special naming convention:
- /mylib/user.php will be equal to MylibUser
- /mylib/userhelper.php will be equal to MylibUserHelper
The Prefix Loader
Since Joomla Platform 12.1 (Joomla! CMS 3+), there is the ability to register where the auto-loader will look based on a class prefix (previously only the «J» prefix was supported, bound to the /libraries/joomla folder). This is done with the registerPrefix() method and allows for several scenarios:
- A developer can register the prefix of custom classes and a root path to allow the auto-loader to find them.
- A developer can register an extra path for an existing prefix. (For example, this allows the Joomla CMS to have custom libraries but still using the «J» prefix.)
- A developer can register a force override for a prefix. This could be used to completely override the core classes with a custom replacement.
Convention
The class name must be in CamelCase and each segment of the name will represent a folder path where the last segment of the name is the name of the class file. If there is only one part to the class name, the auto-loader will look for the file in a folder of the same name. Folder names must be in lower case.
- PrefixUserModel class should be located in PATH_TO_PREFIX/user/model.php
- PrefixUser class should be located in PATH_TO_PREFIX/user/user.php
Our scenario examples:
- MylibUserHelper class should be located in /libraries/mylib/user/helper.php
- MylibUser class should be located in /libraries/mylib/user/user.php
There is no limit to the depth to which the auto-loader will search, providing it forms a valid path based on the CamelCase natural of the class name. Note that while acronyms and names such as HTML, XML and MySQL have a standard presentation in text, such terms should observe CamelCase rules programmatically. («HTML» becomes «Html», «XML» becomes «Xml» and so on.)
Usage
// Tell the auto-loader to look for classes starting with '"Mylib" in a specific folder. JLoader::registerPrefix('Mylib', JPATH_LIBRARIES . '/mylib');
// Tell the auto-loader to also look in the "/libraries/cms" folder for "J" prefixed classes. JLoader::registerPrefix('J', JPATH_PLATFORM . '/cms');
// Tell the auto-loader to reset the "J" prefix and point it to a custom fork of the platform. JLoader::registerPrefix('J', '/my/platform/fork', true);
Note on registerPrefix
For Joomla CMS 2.5, the prefix cannot start with the same letter. The system will try to load the first matched. For example, if we register prefix JM, as J prefix exists, the JLoader will find J prefix. When it searches for the class in the registered path of J, no class will be found.
Namespace Loader
As of Joomla CMS v3.1.2, the core autoloader has support for autoloading PSR-0 style namespaced libraries. (You can study PHP namespaces here.) If you only support Joomla on PHP 5.3+ (which you do if you only support Joomla CMS v3.x or greater), you can utilize code that uses native PHP namespaces. In accordance with PSR-0 rules, the directory and file casing must match that of the PHP namespace and class.
Usage
// Tell the auto-loader to look for namespaced classes starting with MyLib in the JPATH_LIBRARIES/src directory JLoader::registerNamespace('MyLib', JPATH_LIBRARIES . '/src');
Accessing the Library from Anywhere
To access our library from any place in the application, create a system plugin which will register our library with the JLoader. This plugin should fire on onAfterInitialise event:
Manifest File
System - Mylib Joomla! Project March 2013 Copyright (C) 2005 - 2013 Open Source Matters. All rights reserved. GNU General Public License version 2 or later. admin@joomla.org www.joomla.org 1.0.0 Simple example plugin to register custom library. mylib.php index.html
Plugin File
Now you will be able to call classes from your library (located in /libraries/mylib) from any component, module or plugin.