Jump to content

is there a better way? rendering fields, wrapped in code, if filled, repeatedly


Recommended Posts

frequently i do something like the following expanded simple version....

foreach ($foos as $foo) {

	// always a title & link
	$title = "
		<h1 class='foo__title'>
			<a href='{$foo->url}'>
	// sometimes a headline
	$headline = NULL;
	if ($page->headline){
		$headline = "
			<h2 class='page__headline'>

	echo "
		<div class='foo'>

the short take away is that i...

  • know certain fields will exist, and i want to wrap them in specific tags/classes
  • have fields that might exist, and i want to wrap them in specific tags/classes  or output nothing silently
  • want to wrap all of the output

Probably due to inexperience, I haven't found a slick way to simplify this pattern for myself. Using a function and arguments seems very messy to me because it can get complicated to maintain as pieces need to change. maybe I just write crappy functions.

Do you guys have a very maintainable way to output a fields value, always wrapped in specific tag/class, but only if it exists?


Link to comment
Share on other sites

I agree with @abdus that field rendering is the solution.

But if you're just wanting a tidier way of doing what you are already doing then you can rewrite it as:

<?php foreach($foos as $foo): ?>
    <div class="foo">
        <h1 class="foo__title">
            <a href="<?= $foo->url ?>"><?= $foo->title ?></a>
        <?php if($page->headline): ?>
            <h2 class="page__headline"><?= $page->headline ?></h2>
        <?php endif; ?>
<?php endforeach; ?>


  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...