Create loop in templates with php

Asked

Viewed 374 times

1

I’m having trouble creating an algorithm to implement the use of loops in a class of template simple.

I have my class below, it gets an HTML file, looks for strings specifies that are in this file from values of a array and replaced by another string obtained from a variable, finally returns the changed HTML code in the form of print on the screen. Works very well, except when I need to use loops.

Note: I want to separate all my HTML code from PHP

Template class

<?php

class Template {

private $file;
private $vars;

public function __construct($file = "") {

    $this->vars = array();
    $this->load($file);
}

public function load($file){

    if(file_exists($file)){

        if(file_get_contents($file)){

            $this->file = file_get_contents($file);

            return true;
        }
        else{

            return die("Error: Could not load file \"{$file}.\"");
        }
    }
    else{

        return die("Error: file \"{$file}\" not found.");
    }
}

public function show(){

    if($this->file){

        $output = $this->file;

        foreach ($this->vars as $varName => $varValue) {

            $tagToReplace = "{{$varName}}";

            $output = str_replace($tagToReplace, $varValue, $output);
        }

        printf($output);
    }
    else {
        return die("Error: template file is empty.");
    }
}

public function setVar($varName, $varValue){

    if(!empty($varName) && !empty($varValue)){

        $this->vars[$varName] = $varValue;
    }
}
}
?>

Example of use index php.

<?php

$template   = new Template("index.template.html");

$template->setVar("page_title", "Página Inicial");
$template->setVar("msg", "Bem vindo!");

$template->show();
?>

Filing cabinet index.template.html

<!DOCTYPE html>
<html>
    <head>
        <title>{page_title}</title>
    </head>
    <body>
        <h1>{msg}</h1>
    </body>
</html>
  • Where do you want to use these loops? I don’t understand very well...

  • Do you want to be able to use more than one variable? For example, two <h1>?

  • Ah ta ta.. It’s in the foreach the problem. =)

2 answers

0

I don’t quite know how you want it to be printed at the end. But for you to use all variables in the array you should treat them separately from the code that makes the HTML change. An example:

    // ... código anterior

    $tagToReplace = "{{$varName}}";
    $newValue = ""; // criei essa variável para ser usada depois

    foreach ($this->vars as $varName => $varValue) {

        $newValue .= $varValue." ";

    }
    // aqui ele altera com a variável $newValue
    $output = str_replace($tagToReplace, $newValue, $output); 

    // restante do código ...

I believe it will work. Any error comment here below. Hug!

  • Andrei, the show() method goes through the values of the $vars array, and searches the $file variable that received the content of the html file, a string identical to the current key of $vars, if it finds it replaces it with the current value of $vars, and at the end it prints the changed html code on the screen. This way I change one by one the pre-defined data of an html file before printing it on the screen, what I need is a solution for when I need to use a loop, to return data from a query in the database among other cases.

  • @Alexoliveira then did not understand your question. Where you might need to use this loop in this class, in the load function for example, or in HTML?

  • Right. With that you wanted what? Put more than one <h1>? For example? Or other tags? Is that it? Or putting more than one information on <h1>? That’s what I’m trying to understand.

  • I need to implement this in the function Show(); For those who already use some framework that has a template engine, usually work on two concepts, variables (that I already use) and blocks, the blocks contain variables also the difference is that the contents of the block will be repeated while there is data to be returned.

-1

What you have done so far is very simple, so obviously if you want to get something more generic or complete you will have to go much further. This way, you just bumped into the first problem (loops), but you will bump into conditional, and several other problems. So there are projects where other people have thought, chewed for the community very complete and robust solutions that do exactly what they are trying to do. One example is Smarty: http://www.smarty.net/

The documentation is great because it is a very complete solution. My suggestion is to search for PHP Template Engines on google and choose the one that best suits you.

  • Paul, thank you so much for the tip! I hear and see a lot of people commenting on the potential of frameworks that have template engine, but at the exact moment I look for only one solution to this problem, I am interested in understanding the algorithm used in cases like this. .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.