
One of sGen's greatest strengths is the ability to easily work with data from a database, without burdening the designer with a bizarre tag structure.
Completing this tutorial will require some knowledge of Serenity's data layer, which is covered in the Hello World tutorial ( at the end ).
First, open your action handler. We'll connect to the database and pull some rows from the Hello.table that we set up in the Hello World tutorial.
Add the following code to connect to the table and assign the data to sGen ( we'll explain the function further down ):
$Hello = Serenity::data()->open('Hello.table'); $Hello->add_restriction( 'id<10' ); if( $Hello->get() ) { Serenity::output()->add_data( 'HelloData', $Hello ); } else { Serenity::output()->add_message( 'HelloData', 'No hellos found!' ); }
As you can see above, the add_data() call will assign the database table instance $Hello, to the tag HelloData if rows are found.
If rows are not found, the add_message() call instead will assign the message 'No hellos found!' to the HelloData tag. We'll populate the HTML template first before explaining how this works.
Open your tpl-global.php template and change the HTML to the following:
<html> <head><title><sgen vars="title" /></title> <link rel="stylesheet" href="<sgen config="style_path" />/style.css" type="text/css" /> </head> <body> This is the in the wrapper: <sgen vars="username" /> <sgen bits="body_content" /> <sgen data="HelloData"> I found a hello! Here it is: <sgen:text /> and it's ID# <sgen:id /> </sgen> </body> </html>
Now that the data tag has been added, you can see how it relates back to the add_data() and add_message() sGen functions. Keep in mind that if no rows are found and you have assigned a message to the data tag, sGen will erase the data tag and all contents, and replace it with the text assigned using add_message(). If no message has been set, sGen will simply erase the data tag on output.
Another note on the data tag, to access members of the data, you use the syntax <sgen:key_name /> This syntax is only valid inside of a data tag. In the database example above, the key_name is mapped to the column name coming from the database row.
The data tag also understands array() types. To use an array with the above example, erase the data() call and if/else, replacing it with something like the following:
$myData = array( 'id' => 5, 'text' => 'Hai there.' ); Serenity::output()->add_data( 'HelloData', $myData );
Next let's look at adding a widget to a template.