Accessing Data in Templates
When a $data
array is passed into a view file or a template, all properties of the $data
array are accessible within those contexts. For example, if the $data
array contains a 'name' property of 'John' and an 'age' property of 21, these details can be rendered as follows:
<?php echo $name.' '.$age; ?>
Additionally, to inspect all properties within the $data
array, you can use var_dump($data)
, print_r($data)
, or Trongate's json()
function within the view file or template. For example:
<?= json($data) ?>
In Summary
- Templates provide the overall structure for web pages.
- View files contain specific content that is injected into a web page.
- Trongate's template() method should be used to load templates.
- Information can be passed into templates and views in the form of an array.
- If content from view files is to be injected into a template, a 'view_file' property should be initialized as part of a
$data
array. - The value of the 'view_file' property should be equal to the file name of the target view file, but without the .php suffix. For example:
- When injecting a 'view_file' property into a template, it is good practice to also initialize a 'view_module' property. This gives the framework clear instructions as to the location of the target view file. For example:
- If the first segment of the URL matches the module name calling the template, the 'view_module' declaration can be omitted.
- Within template files, the following PHP code should be added to signify where view file content should appear:
- Trongate's json() function can be used from within a template or a view file to confirm what properties have been passed in. For example:
$data['view_file'] = 'homepage_content';
$data['view_module'] = 'welcome';
$data['view_file'] = 'homepage_content';
<?= Template::display($data) ?>
<?= json($data) ?>