06. Create dynamic pages - ihofmann/open-websoccer GitHub Wiki

Create dynamic pages with Models

Dynamic pages display non-static content, like data from the database or content which depends on user input. These pages use "model classes" which provide the data for the templates.

In the following, we will create a page displaying "Hello {user name}".

Create a new module

We first create a new module called "hello".

  1. Create new folder: /modules/hello
  2. Create new file: /modules/hello/module.xml
  3. Create new file: /modules/hello/messages_en.xml
  4. Create new file: /templates/default/views/hello.twig
  5. Create new file: /classes/models/HelloModel.class.php

module.xml

The file module.xml has following content:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE module SYSTEM "../module.dtd">
<module version="1.0.0">
	
	<pages>
		<page
			id="hello"
			template="hello"
			navitem="true"
			navweight="5"
			model="HelloModel"
			role="user" />
	</pages> 
  
</module>

The meaning of the attributes are explained at chapter Create new pages. We only added the attribute model which points to the class file that we have just created.

messages_en.xml

The file messages_en.xml has following content:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE messages SYSTEM "../messages.dtd">
<messages>
	<message id="hello_navlabel">Hello</message>
	<message id="hello_content">Hello:</message>
</messages>

hello.twig

The template file:

{% extends "base.twig" %}

{% block page_title %}
{{ i18n.getMessage("hello_navlabel") }}
{% endblock %}

{% block page_content %}

<p>{{ i18n.getMessage("hello_content") }} {{ username }}</p>

{% endblock %}

Have you recognized the placeholder _username:? This will by filled by the model class that we are going to create in the next step.

HelloModel.class.php

Model classes fill the placeholders of a template. These can react on request parameters or provide data from the data base. For now, we only want to retrieve the current user's user name.

class HelloModel implements IModel {
	private $_db;
	private $_i18n;
	private $_websoccer;
	
	public function __construct($db, $i18n, $websoccer) {
		$this->_db = $db;
		$this->_i18n = $i18n;
		$this->_websoccer = $websoccer;
	}
	
	public function renderView() {
		return TRUE;
	}
	
	public function getTemplateParameters() {
		
		$user = $this->_websoccer->getUser();
		
		$username = $user->username;
		
		return array("username" => $username);
	}
	
}

Publishing

Follow these steps in order to publish the new page:

  1. Upload the created file to your web server.
  2. Log on to the AdminCenter.
  3. Click on "Empty Cache".
⚠️ **GitHub.com Fallback** ⚠️