Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Data Fields | Protected Member Functions | Protected Attributes
Template Class Reference
Inheritance diagram for Template:
AbstractBlock DataObject BlockInterface SearchData RequireJs Template ColumnSet Serializer Payment Button Captcha DefaultCaptcha Edit Error Qty Result Serializer Container Link Breadcrumbs Link View FrontendStorageManager Navigation AbstractProduct Gallery Image Price Toolbar TemplateSelector Additional Attributes Description Options AbstractOptions Price Tabs ShortcutButtons ProductViewCounter Render Qtyincrements AbstractStockqty Form Result Result AbstractCart Info Configure Renderer Generic Renderer Onepage Failure Link Success Registration Success Agreements Block ContactForm Notices RequireCookie AuthenticationPopup Customer Dashboard Address Info Delimiter Forgotpassword Resetpassword Book CustomerData CustomerScopeData Login Info SectionConfig AbstractWidget Currency Data ListProducts AbstractAdjustment Amount PriceBox Calendar Date Link Current Links Components Cookie Template Messages Redirect Inline Code Ga AbstractCode Button Navigation FilterRenderer State Popup Total AbstractMultishipping Link State Subscribe Javascript Form Container Info AbstractContainer Iframe Info View Agreements Banners Shortcut BillingAgreement Component Button Review Billing Shipping Shortcut Logo Remember AbstractEmail View Link Recent Form Review ReviewRenderer Other Detailed Feeds Load Details Link AbstractItems Comments DefaultItems DefaultOrder History Container Info Buttons Rss DefaultRenderer Recent Totals View Sidebar Form Coupons Term Send Shipment Ajax Popup CaseInfo Fingerprint Switcher Switcher Index RenderLayered Title Renderer Tax Breadcrumbs Footer Header Logo Notices Pager Title Topmenu Welcome Js StepsWizard StepAbstract Logger Wrapper ActiveEditor Button Nav UiComponent AbstractTokenRenderer PaymentTokens Totals AddToWishlist Sharing Button Items Configure Link

Public Member Functions

 __construct (Template\Context $context, array $data=[])
 
 setTemplateContext ($templateContext)
 
 getTemplate ()
 
 setTemplate ($template)
 
 getTemplateFile ($template=null)
 
 getArea ()
 
 assign ($key, $value=null)
 
 fetchView ($fileName)
 
 getBaseUrl ()
 
 getObjectData (\Magento\Framework\DataObject $object, $key)
 
 getCacheKeyInfo ()
 
- Public Member Functions inherited from AbstractBlock
 __construct (\Magento\Framework\View\Element\Context $context, array $data=[])
 
 getJsLayout ()
 
 getRequest ()
 
 getParentBlock ()
 
 setLayout (\Magento\Framework\View\LayoutInterface $layout)
 
 getLayout ()
 
 setNameInLayout ($name)
 
 getChildNames ()
 
 setAttribute ($name, $value=null)
 
 setChild ($alias, $block)
 
 addChild ($alias, $block, $data=[])
 
 unsetChild ($alias)
 
 unsetCallChild ($alias, $callback, $result, $params)
 
 unsetChildren ()
 
 getChildBlock ($alias)
 
 getChildHtml ($alias='', $useCache=true)
 
 getChildChildHtml ($alias, $childChildAlias='', $useCache=true)
 
 getBlockHtml ($name)
 
 insert ($element, $siblingName=0, $after=true, $alias='')
 
 append ($element, $alias='')
 
 getGroupChildNames ($groupName)
 
 getChildData ($alias, $key='')
 
 getUiId ($arg1=null, $arg2=null, $arg3=null, $arg4=null, $arg5=null)
 
 getJsId ($arg1=null, $arg2=null, $arg3=null, $arg4=null, $arg5=null)
 
 getUrl ($route='', $params=[])
 
 getViewFileUrl ($fileId, array $params=[])
 
 formatDate ( $date=null, $format=\IntlDateFormatter::SHORT, $showTime=false, $timezone=null)
 
 formatTime ( $time=null, $format=\IntlDateFormatter::SHORT, $showDate=false)
 
 getModuleName ()
 
 escapeHtml ($data, $allowedTags=null)
 
 escapeJs ($string)
 
 escapeHtmlAttr ($string, $escapeSingleQuote=true)
 
 escapeCss ($string)
 
 stripTags ($data, $allowableTags=null, $allowHtmlEntities=false)
 
 escapeUrl ($string)
 
 escapeXssInUrl ($data)
 
 escapeQuote ($data, $addSlashes=false)
 
 escapeJsQuote ($data, $quote='\'')
 
 getNameInLayout ()
 
 getCacheKeyInfo ()
 
 getCacheKey ()
 
 getVar ($name, $module=null)
 
 isScopePrivate ()
 
- Public Member Functions inherited from DataObject
 __construct (array $data=[])
 
 addData (array $arr)
 
 setData ($key, $value=null)
 
 unsetData ($key=null)
 
 getData ($key='', $index=null)
 
 getDataByPath ($path)
 
 getDataByKey ($key)
 
 setDataUsingMethod ($key, $args=[])
 
 getDataUsingMethod ($key, $args=null)
 
 hasData ($key='')
 
 toArray (array $keys=[])
 
 convertToArray (array $keys=[])
 
 toXml (array $keys=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 convertToXml (array $arrAttributes=[], $rootName='item', $addOpenTag=false, $addCdata=true)
 
 toJson (array $keys=[])
 
 convertToJson (array $keys=[])
 
 toString ($format='')
 
 __call ($method, $args)
 
 isEmpty ()
 
 serialize ($keys=[], $valueSeparator='=', $fieldSeparator=' ', $quote='"')
 
 debug ($data=null, &$objects=[])
 
 offsetSet ($offset, $value)
 
 offsetExists ($offset)
 
 offsetUnset ($offset)
 
 offsetGet ($offset)
 
- Public Member Functions inherited from BlockInterface
 toHtml ()
 

Data Fields

const XML_PATH_TEMPLATE_ALLOW_SYMLINK = 'dev/template/allow_symlink'
 
- Data Fields inherited from AbstractBlock
const CACHE_GROUP = \Magento\Framework\App\Cache\Type\Block::TYPE_IDENTIFIER
 
const CACHE_KEY_PREFIX = 'BLOCK_'
 

Protected Member Functions

 _construct ()
 
 _toHtml ()
 
 getRootDirectory ()
 
 getMediaDirectory ()
 
- Protected Member Functions inherited from AbstractBlock
 _construct ()
 
 _prepareLayout ()
 
 _beforeToHtml ()
 
 _afterToHtml ($html)
 
 _toHtml ()
 
 _getNotFoundUrl ($route='', $params=['_direct'=> 'core/index/notFound'])
 
 getCacheTags ()
 
 getCacheLifetime ()
 
 _loadCache ()
 
 _saveCache ($data)
 
 _getSidPlaceholder ($cacheKey=null)
 
- Protected Member Functions inherited from DataObject
 _getData ($key)
 
 _underscore ($name)
 

Protected Attributes

 $_viewVars = []
 
 $_baseUrl
 
 $_jsUrl
 
 $_allowSymlinks
 
 $_filesystem
 
 $_template
 
 $templateEnginePool
 
 $_storeManager
 
 $_appState
 
 $directory
 
 $templateContext
 
 $pageConfig
 
 $resolver
 
 $validator
 
- Protected Attributes inherited from AbstractBlock
 $_design
 
 $_session
 
 $_sidResolver
 
 $_nameInLayout
 
 $_layout
 
 $jsLayout = []
 
 $_request
 
 $_urlBuilder
 
 $_eventManager
 
 $_frontController
 
 $_assetRepo
 
 $_viewConfig
 
 $_cacheState
 
 $_logger
 
 $_escaper
 
 $filterManager
 
 $_localeDate
 
 $inlineTranslation
 
 $_isScopePrivate = false
 
 $_scopeConfig
 
 $_cache
 
- Protected Attributes inherited from DataObject
 $_data = []
 

Additional Inherited Members

- Static Public Member Functions inherited from AbstractBlock
static extractModuleName ($className)
 
- Static Protected Attributes inherited from DataObject
static $_underscoreCache = []
 

Detailed Description

Standard Magento block. Should be used when you declare a block in frontend area layout handle.

Avoid extending this class.

If you need custom presentation logic in your blocks, use this class as block, and declare custom view models in block arguments in layout handle file.

Example: <block name="my.block" class="Magento\Backend\Block\Template" template="My_Module::template.phtml"> <arguments> <argument name="viewModel" xsi:type="object">My\Module\ViewModel\Custom</argument> </arguments> </block>

@api @SuppressWarnings(PHPMD.NumberOfChildren) @SuppressWarnings(PHPMD.CouplingBetweenObjects)

Since
100.0.2

Definition at line 32 of file Template.php.

Constructor & Destructor Documentation

◆ __construct()

__construct ( Template\Context  $context,
array  $data = [] 
)

Constructor

Parameters
Template\Context$context
array$data

Definition at line 144 of file Template.php.

145  {
146  $this->validator = $context->getValidator();
147  $this->resolver = $context->getResolver();
148  $this->_filesystem = $context->getFilesystem();
149  $this->templateEnginePool = $context->getEnginePool();
150  $this->_storeManager = $context->getStoreManager();
151  $this->_appState = $context->getAppState();
152  $this->templateContext = $this;
153  $this->pageConfig = $context->getPageConfig();
154  parent::__construct($context, $data);
155  }

Member Function Documentation

◆ _construct()

_construct ( )
protected

Internal constructor, that is called from real constructor

Returns
void

Definition at line 172 of file Template.php.

173  {
174  parent::_construct();
175 
176  /*
177  * In case template was passed through constructor
178  * we assign it to block's property _template
179  * Mainly for those cases when block created
180  * not via \Magento\Framework\View\Model\LayoutInterface::addBlock()
181  */
182  if ($this->hasData('template')) {
183  $this->setTemplate($this->getData('template'));
184  }
185  }
getData($key='', $index=null)
Definition: DataObject.php:119

◆ _toHtml()

_toHtml ( )
protected

Render block HTML

Returns
string

Definition at line 296 of file Template.php.

297  {
298  if (!$this->getTemplate()) {
299  return '';
300  }
301  return $this->fetchView($this->getTemplateFile());
302  }

◆ assign()

assign (   $key,
  $value = null 
)

Assign variable

Parameters
string | array$key
mixed$value
Returns
$this

Definition at line 242 of file Template.php.

243  {
244  if (is_array($key)) {
245  foreach ($key as $subKey => $subValue) {
246  $this->assign($subKey, $subValue);
247  }
248  } else {
249  $this->_viewVars[$key] = $value;
250  }
251  return $this;
252  }
$value
Definition: gender.phtml:16

◆ fetchView()

fetchView (   $fileName)

Retrieve block view from file (template)

Parameters
string$fileName
Returns
string

Definition at line 260 of file Template.php.

261  {
262  $relativeFilePath = $this->getRootDirectory()->getRelativePath($fileName);
263  \Magento\Framework\Profiler::start(
264  'TEMPLATE:' . $fileName,
265  ['group' => 'TEMPLATE', 'file_name' => $relativeFilePath]
266  );
267 
268  if ($this->validator->isValid($fileName)) {
269  $extension = pathinfo($fileName, PATHINFO_EXTENSION);
270  $templateEngine = $this->templateEnginePool->get($extension);
271  $html = $templateEngine->render($this->templateContext, $fileName, $this->_viewVars);
272  } else {
273  $html = '';
274  $templatePath = $fileName ?: $this->getTemplate();
275  $errorMessage = "Invalid template file: '{$templatePath}' in module: '{$this->getModuleName()}'"
276  . " block's name: '{$this->getNameInLayout()}'";
277  if ($this->_appState->getMode() === \Magento\Framework\App\State::MODE_DEVELOPER) {
278  throw new \Magento\Framework\Exception\ValidatorException(
279  new \Magento\Framework\Phrase(
280  $errorMessage
281  )
282  );
283  }
284  $this->_logger->critical($errorMessage);
285  }
286 
287  \Magento\Framework\Profiler::stop('TEMPLATE:' . $fileName);
288  return $html;
289  }
$fileName
Definition: translate.phtml:15

◆ getArea()

getArea ( )

Get design area

Returns
string

Definition at line 230 of file Template.php.

231  {
232  return $this->_getData('area') ? $this->_getData('area') : $this->_appState->getAreaCode();
233  }

◆ getBaseUrl()

getBaseUrl ( )

Get base url of the application

Returns
string

Definition at line 309 of file Template.php.

310  {
311  if (!$this->_baseUrl) {
312  $this->_baseUrl = $this->_urlBuilder->getBaseUrl();
313  }
314  return $this->_baseUrl;
315  }

◆ getCacheKeyInfo()

getCacheKeyInfo ( )

Get cache key informative items

Returns
array

Definition at line 334 of file Template.php.

335  {
336  return [
337  'BLOCK_TPL',
338  $this->_storeManager->getStore()->getCode(),
339  $this->getTemplateFile(),
340  'base_url' => $this->getBaseUrl(),
341  'template' => $this->getTemplate()
342  ];
343  }

◆ getMediaDirectory()

getMediaDirectory ( )
protected

Get media directory

Returns
\Magento\Framework\Filesystem\Directory\Read

Definition at line 364 of file Template.php.

365  {
366  if (!$this->mediaDirectory) {
367  $this->mediaDirectory = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA);
368  }
369  return $this->mediaDirectory;
370  }
$mediaDirectory

◆ getObjectData()

getObjectData ( \Magento\Framework\DataObject  $object,
  $key 
)

Get data from specified object

Parameters
\Magento\Framework\DataObject$object
string$key
Returns
mixed

Definition at line 324 of file Template.php.

325  {
326  return $object->getDataUsingMethod((string)$key);
327  }

◆ getRootDirectory()

getRootDirectory ( )
protected

Instantiates filesystem directory

Returns
\Magento\Framework\Filesystem\Directory\ReadInterface

Definition at line 350 of file Template.php.

351  {
352  if (null === $this->directory) {
353  $this->directory = $this->_filesystem->getDirectoryRead(DirectoryList::ROOT);
354  }
355 
356  return $this->directory;
357  }

◆ getTemplate()

getTemplate ( )

Get relevant path to template

Returns
string

Definition at line 192 of file Template.php.

193  {
194  return $this->_template;
195  }

◆ getTemplateFile()

getTemplateFile (   $template = null)

Get absolute path to template

Parameters
string | null$template
Returns
string|bool

Definition at line 215 of file Template.php.

216  {
217  $params = ['module' => $this->getModuleName()];
218  $area = $this->getArea();
219  if ($area) {
220  $params['area'] = $area;
221  }
222  return $this->resolver->getTemplateFileName($template ?: $this->getTemplate(), $params);
223  }
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18
$template
Definition: export.php:12

◆ setTemplate()

setTemplate (   $template)

Set path to template used for generating block's output.

Parameters
string$template
Returns
$this

Definition at line 203 of file Template.php.

204  {
205  $this->_template = $template;
206  return $this;
207  }
$template
Definition: export.php:12

◆ setTemplateContext()

setTemplateContext (   $templateContext)

Set template context. Sets the object that should represent $block in template

Parameters
\Magento\Framework\View\Element\BlockInterface$templateContext
Returns
void

Definition at line 163 of file Template.php.

164  {
165  $this->templateContext = $templateContext;
166  }

Field Documentation

◆ $_allowSymlinks

$_allowSymlinks
protected

Definition at line 65 of file Template.php.

◆ $_appState

$_appState
protected

Definition at line 100 of file Template.php.

◆ $_baseUrl

$_baseUrl
protected

Definition at line 51 of file Template.php.

◆ $_filesystem

$_filesystem
protected

Definition at line 72 of file Template.php.

◆ $_jsUrl

$_jsUrl
protected

Definition at line 58 of file Template.php.

◆ $_storeManager

$_storeManager
protected

Definition at line 93 of file Template.php.

◆ $_template

$_template
protected

Definition at line 79 of file Template.php.

◆ $_viewVars

$_viewVars = []
protected

Definition at line 44 of file Template.php.

◆ $directory

$directory
protected

Definition at line 107 of file Template.php.

◆ $pageConfig

$pageConfig
protected

Definition at line 126 of file Template.php.

◆ $resolver

$resolver
protected

Definition at line 131 of file Template.php.

◆ $templateContext

$templateContext
protected

Definition at line 121 of file Template.php.

◆ $templateEnginePool

$templateEnginePool
protected

Definition at line 86 of file Template.php.

◆ $validator

$validator
protected

Definition at line 136 of file Template.php.

◆ XML_PATH_TEMPLATE_ALLOW_SYMLINK

const XML_PATH_TEMPLATE_ALLOW_SYMLINK = 'dev/template/allow_symlink'

Config path to 'Allow Symlinks' template settings

Definition at line 37 of file Template.php.


The documentation for this class was generated from the following file: