06. Create dynamic pages - ihofmann/open-websoccer GitHub Wiki
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}".
We first create a new module called "hello".
- Create new folder: /modules/hello
- Create new file: /modules/hello/module.xml
- Create new file: /modules/hello/messages_en.xml
- Create new file: /templates/default/views/hello.twig
- Create new file: /classes/models/HelloModel.class.php
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.
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>
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.
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);
}
}
Follow these steps in order to publish the new page:
- Upload the created file to your web server.
- Log on to the AdminCenter.
- Click on "Empty Cache".