I created a site that has a News section. I created news-item subpages that act as the singular news articles (think: blog/blog-entry). Those news-items are all rendered into the News template.
The current structure looks like this:
content
—3-news
——this-is-a-news-item
——another-headline-news
——hello-world-news
site
—templates
——news
——news-item
I would also like to render those news-item[s] out on the homepage as well. Is there a way to specifically query for those subpages and show them outside of their normal parent template?
Here’s how I’m currently rendering each news-item out onto the News page:
<?php foreach($page->children()->sortBy('date','desc') as $news): ?>
<div>
<div class="news-item">
<?php if (!empty($news->file())) { ?>
<img src="<?php echo $news->file()->url() ?>" />
<?php } ?>
<em><?php echo $news->date('F d, Y') ?></em>
<h3><?php echo $news->title()->html() ?></h3>
<p><?php echo $news->text() ?></p>
</div>
</div>
<?php endforeach ?>
Yes, of course:
$articles = page('blog')->children()->sortBy('date', 'desc');
Then you just iterate through the collection as above.
Hi Texnixe, forgive me, I’m obviously a total noob with this…
The main section is called “news”. Are you suggesting I replace the foreach with some of what you outlined?
`<?php foreach($page('news')->children()->sortBy('date', 'desc'): ?>
…
<?php endforeach ?>`
Doing so results in an error:
‘Fatal error: Function name must be a string in /Users/username/-/kirby-project/kirby/site/templates/home.php on line 43’
----------------UPDATE------------------
I have it working, although not certain if this is the cleanest way to do it?
<?php foreach((page('news')->children()->sortBy('date', 'desc')) as $news): ?>
<div><div class="news-item">
<?php if (!empty($news->file())) { ?>
<img src="<?php echo $news->file()->url() ?>" />
<?php } ?>
<em><?php echo $news->date('F d, Y') ?></em>
<h3><?php echo $news->title()->html() ?></h3>
<p><?php echo $news->text() ?></p>
</div></div>
<?php endforeach ?>
It’s not $page('news')
but page('news')
without the $
sign. You can also save it into a variable first like I did above and then use the variable in your foreach loop:
<?php
$news = page('news')->children()->sortBy('date', 'desc');
foreach($news as $newsItem): ?>
//do stuff
<?php endforeach ?>
Pls note that I changed the variable to newsItem
so you have to adapt your code above to reflect this.
1 Like
Excellent. Understood. Thanks very much!