darrenc Posted October 27, 2017 Share Posted October 27, 2017 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}'> {$foo->title} </a> </h1> "; // sometimes a headline $headline = NULL; if ($page->headline){ $headline = " <h2 class='page__headline'> {$page->headline} </h2> "; } echo " <div class='foo'> $title $headline </div> "; } 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 More sharing options...
abdus Posted October 27, 2017 Share Posted October 27, 2017 Check out field rendering https://processwire.com/blog/posts/processwire-3.0.7-expands-field-rendering-page-path-history-and-more/#field-rendering-with-template-files 2 Link to comment Share on other sites More sharing options...
Robin S Posted October 27, 2017 Share Posted October 27, 2017 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> </h1> <?php if($page->headline): ?> <h2 class="page__headline"><?= $page->headline ?></h2> <?php endif; ?> </div> <?php endforeach; ?> 2 Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now