How can I use php variables with Slim Framework?


#1

I’m trying to populate a page with information based on what id is selected by the user. I have tried defining my variables using the slim framework but I’m confused as to how to use them or call them. My variables are stored on the listings.php page, and I’m trying to call the on the listings.html page.

I’ve included the relevant code below. On a different page, the user can select a database entry to share:

<div class="list-option">
<a href="/listings/share/{{listing.id}}" class="option-button settings">Share Listing</a>
</div>

If I select a specific item (for example item 34), the URL appears as:

.../listings/share/34

But now I want to populate that share.html page with all relevant information from item 34 of the listings table. My listings.php page looks like this to extract the data from the database:

$app->get('/listings/share/{lisitingid}', function ($request, $response, $args) {

    $variables['title'] = 'Share Listing';
    $variables['listing'] = $this->db->select('listing', ['id', 'name', 'details', 'associated_user', 'address', 'location', 'category']);

    return $this->view->render ($response, 'share.html', $variables);
});

And my share.html page looks like this:

<div class='wrapper'>
    <div class='listing-image'>
    <img src='###'>
    </div>
    <div class='listing-info'>
    <div class='listing-title'>
        <div class='lister-logo'><img src='image/###' alt='Lister Logo'></div>
        <div class='listing-category'>.$row['category']."'</div>
        <h2 class='listing-name'></h2></div>
    <div class='profile-pic'><img src='image/###' alt='profile picture'></div>
    <div class='lister-bio'>
        <h2 class='about'>.$row['name']</h2></div>

        <p class='biography'>".$row['details']"</p>
    </div>
    <div class='lister-contact'>
        <div class='address'>".$row['address']</div>

I know this is wrong, I’m trying to use a previous method I know for calling information from a database but I’m using Slim framework and its totally new to me. Would anybody be able to demonstrate or show me how I can get the information from the database to show on the share.html page based on what I have attempted?


#2

The view data must always be passed to the template. Never fetch data within the template from the database, this would break the MVC concept. Are you using Twig or PHP templates? I’m asking this, because your first template looks like Twig and the second template like a (invalid) PHP template file.


#3

I’m using Twig yes. How them do I use the variables on the html page?


#4

The Twig documentation shows you how to use variables:

https://twig.symfony.com/doc/2.x/templates.html#variables

You can use a dot ( . ) to access attributes of a variable:

Example:

<h1>{{ listing.name }}</h1>