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?


Share this post

Link to post
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

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Create New...