1

I have a simple template engine that works fine the simple template, but I don't know how to adapt it to make it work with loops :

class Template {

   public $template;

   function getFile($file) {
      $this->template = file_get_contents($file);
   }

   function set($tag, $content) {
      $this->template = str_replace("{".$tag."}", $content, $this->template);
   }

   function ouput() {
      eval("?>".$this->template."<?");
   }
}

That's the loop I want to parse and display:

{{#each Stuff}}
  {{Thing}} are {{Desc}}
{{/each}}

I dont want use any SMARTY or Twig engine. Any idea please?

3
  • check this blade template, this is used by a popular framework, Laravel. Commented Jan 22, 2018 at 17:27
  • You just need a syntax that you can read and do foreach. Example: for[space]var[space]in[space]original_var: you could explode [space] and then execute a foreach based on var and original var. Commented Jan 22, 2018 at 17:29
  • 1
    @Marco could you populate an answer please ? Commented Jan 22, 2018 at 17:32

1 Answer 1

1

Ok, keep in mind this is just for learning purposes. You can't ask on SO for the whole code, you need to try and post question about your tries.

This code parse a string for a foreach and then executes it:

<?php
$var = array(2, 4);

$str = 'for i in var';
$a = explode(' ', $str);

foreach (${$a[3]} as $i => $value)
{
    echo $value;
}

Read this part from PHP docs to understand what i did.

Sign up to request clarification or add additional context in comments.

2 Comments

This doesnt help in my case, could you do it with my case please ?
You need to be more specific of what you need, and you need to show something that you have tried. Please read this stackoverflow.com/help/how-to-ask

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.