1

I like to use php function with template

Let me clarify why i want this I creating a template system that update or create view files in php dynamically.

function body($x = 1) { ?>
    <?php if ($x == 1) { ?>
        Congregates there is one
        ?>
        <div class="container"> Test <?= $x ?>
        <?php
    }
}?>

But then it just print/echo it not i want, i want can capture it as a string. There is heredoc or nowdoc but that is not good with if, elseif, else, foreach etc. like how can i use condition here.

function child0($x = 4) {
    return<<<HTML
    <div class="container"> Test 
    $x
    </div> 
HTML;
}

Some Old question suggesting a complicate system for using heredoc/nowdoc

Puneet Sharma
  • 307
  • 3
  • 9
  • 1
    `function body($x = 1) { if ($x == 1) { $str = "Congregates there is one"; $str. ='
    Test'.$x; } return $str; }` . Not sure if that's what you really mean though.
    – ADyson May 18 '23 at 12:52
  • 1
    _I like to use php function with template like_ Thats almost unreadable. Ween yourself off such ugly code, then you might get syntactically correct code that works :) – RiggsFolly May 18 '23 at 12:53
  • @RiggsFolly it is system that never need to take a look as we are create a file that for view php only but not intended to direct edit you will edit in our template system – Puneet Sharma May 18 '23 at 13:07

1 Answers1

2

Just wrap the HTML section inside ob_start and ob_get_clean. Anything that is written to output gets buffered:

function body($x = 1) {
    ob_start();
    if ($x == 1) {
        ?>
        <div class="container">
            Test <?php echo $x; ?>
        </div>
        <?php
    }
    return ob_get_clean();
}
Salman A
  • 262,204
  • 82
  • 430
  • 521