Trongate Docs
switch to dark modeswitch to dark mode
»
»
Passing View Files Into Templates

Passing View Files Into Templates

Let's assume that you have an ordinary view file inside a module.  We'll assume that our view file is called greeting.php and that it accepts a 'name' value as well as an 'age' value, from a greeting() method.

This means that our greeting method may look like this:

function greeting() {
    $data['name'] = 'John';
    $data['age'] = 21;
    $this->view('greeting', $data);
}

As for our view file?  It might contain some simple HTML that may echo (display) our two variables.  For example:

sample view file

Everything we've done here displays a view file and should work without any problems.  However, if you'd like to have your entire view file displayed within a page template then this can be easily be achieved by following this simple two step process:

STEP 1: On your 'greeting' method, replace the line that loads the view file with three lines.  These three lines should:

  • declare the name of your module directory
  • declare the name of the view file (stored within your module)
  • load the template

The first line should declare a 'view_module' property and should be set to the folder name of your module.  For example,

$data['view_module'] = 'welcome';

The second line, 'view_file', should declare the name of your view file.  For example:

$data['view_file'] = 'greeting';

The third line should load your template, using Trongate's in-built template() method.  This method accepts two arguments:

  • the name of the template that you'd like to load
  • the data array, containing the information you'd like to pass into the template

For example,

$this->template('public', $data);

So, your complete greeting() method should now look like this:

​​

​​function greeting() {
​​    $data['name'] = 'John';
​​    $data['age'] = 21;
    $data['view_module'] = 'welcome']
​​    $data['view_file'] = 'greeting';
    $this->template('public', $data);
}
​​

STEP 2: Now, open your template view file (public.php).  Go to the area where you'd like your view file to be inserted and add the following line of code:

<?= Template::display($data) ?>

If you've followed along, then your template view file might look something like this:

a template, ready to load a module's view file

Refresh your browser and you should now see your template appearing with your module's view file inside the template.

Top Tip
If the first segment of your URL matches the name of the module that is calling the template, then there's no need to add the 'view_module' declaration to your method.  You can simply leave that line out and Trongate will figure out where your view file is by evaluating the URL.



HELP & SUPPORT

If you have a question or a comment relating to anything you've see here, please goto the Help Bar.

 
×