Jump to content
mike62

Displaying the most recent blog posts using different layouts for each

Recommended Posts

I'm new to PW... I'd like to have some blog posts displayed on our homepage based off the attached mockup.

I want each post to use a slightly different layout.

Is this possible?

blog-posts.jpg

Share this post


Link to post
Share on other sites

Here are two ways:

<?php namespace ProcessWire;
/** @var $pages Pages */
$posts = $pages->find('template=post, sort=-published');
$latest = $posts->shift(); // removes first item off of $posts

?>
<ul class="post-list">
    <li class="item--latest item">
        <?= $latest->title ?>
    </li>
    <?php if ($posts->count): ?>
        <?php foreach ($posts as $i => $p): ?>
            <?php $itemClass = ($i % 3 == 0) ? "item--hoverable" : ''; ?>
            <li class="<?= $itemClass ?> item"><?= $p->title ?></li>
        <?php endforeach; ?>
    <?php endif; ?>
</ul>

<!-- OR -->
<?php if ($posts->count): ?>

    <ul class="post-list">
        <?php foreach ($posts as $i => $post): ?>
            <?php if ($i === 0): // LATEST POST ?>
                <li class="item--latest item">
                    Latest: <?= $post->title ?>
                </li>
            <?php elseif ($i === 1): // BASIC ?>
                <li class="item--basic item">
                    Basic: <?= $post->title ?>
                </li>
            <?php elseif ($i % 3 === 0): // HOVERABLE  ?>
                <li class="item--hoverable item">
                    Hover Me: <?= $post->title ?>
                </li>
            <?php endif; ?>
        <?php endforeach; ?>
    </ul>
<?php else: ?>
    <p>No posts found</p>
<?php endif; ?>

 

Edited by abdus
changed semicolon to colon
  • Like 2

Share this post


Link to post
Share on other sites

Optionally, you can create a select field, or better, a page field and select flavors for each post while editing and render items depending on that

https://processwire.com/blog/posts/making-efficient-use-of-fields-in-processwire/#use-page-fields-rather-than-individual-checkboxes

if($item->flavors->get("name=hoverable")) {
    // this page has the "hoverable" flavor set
}
  • Like 2

Share this post


Link to post
Share on other sites

Ooooh wonderful, that's excellent to know. I likely won't use it for this site, because they want the layout to remain the same on the homepage, and have the content just flow into it, but good to know for the future. Thanks!!

Share this post


Link to post
Share on other sites

@abdus I've got this *almost* working... but I'm stumped with simply getting the sort order to be reversed, so that the newest post shows at the top. Also, can I easily limit this query to 4 posts? Thanks!

Share this post


Link to post
Share on other sites

@kongondo Thanks! I literally JUST found both those in the docs. Some things are hard for me to find in these docs. Is there a way to search *just* the docs, on the site?

Share this post


Link to post
Share on other sites
2 minutes ago, mike62 said:

@kongondo Thanks! I literally JUST found both those in the docs. Some things are hard for me to find in these docs. Is there a way to search *just* the docs, on the site?

https://processwire.com/talk/topic/6196-easy-search-on-pw-forums-with-google/?tab=comments#comment-60632

https://processwire.com/talk/topic/6196-easy-search-on-pw-forums-with-google/?do=findComment&comment=153343

 

  • Like 1

Share this post


Link to post
Share on other sites
3 minutes ago, mike62 said:

*just* the docs, on the site?

I bookmarked these and update the search word after clicking them and press enter. I know it's crude but it is the fastest way for me :-[

Share this post


Link to post
Share on other sites

Thanks for the tip @Robin S I cannot se how it can be faster than my dead simple solution. Sure, I perform an otherwise useless search but Google is sooo fast ;)

With the "keyword search feature", I need to be able to remember the keyword(s). Well, I already use a lot of them in other contexts so I find it hard to memorize more. Next, I need to type the get there. One click in the Bookmarks Bar and another double click to highlight the dummy search word is what I can do quickly without mistakes. Yeah, it's lame but it works for me.

Share this post


Link to post
Share on other sites

Cool, thanks @SamC that's a good one to know. I ended up using the page field as @abdus suggested, so that each post can "choose" its own layout for the homepage. It's working well. o/

  • Like 2

Share this post


Link to post
Share on other sites
12 minutes ago, mike62 said:

Cool, thanks @SamC that's a good one to know. I ended up using the page field as @abdus suggested, so that each post can "choose" its own layout for the homepage. It's working well. o/

Good to hear! That's a nice technique, will certainly be looking into that one.

Share this post


Link to post
Share on other sites

Hey @SamC  I was looking for a way to style some results of a selector differently than others and found your 'slicing' suggestion fitting perfectly to my scenario. Here is a short example of what I have and would allow any results from to be styled one way and the rest - another:

<?php 			
	// Check if there are any news added
	if (count($news->children)) {
		
		// Create am array with the latest 5 news
		$newsposts = $pages->find("template=news-inner, status=published, sort=-date, limit=6");
		
		// Create a slice of 2 posts for the large image style
		// 0 means the starting record, 2 means the number of records to slice
		$left = $newsposts->slice(0,2);
		
		// Grab the rest of the posts from the list for styling with just a title and a date
		// 2 means that everything except the first two would be assigned.
		// The results limit is set initially at the selector
		$right = $newsposts->slice(2);
		
	}
?>

Having done that, it allowed me to simply loop through the $left and $right results (using foreach) and apply the proper markup for first appearance and the rest. Using this elegant technique would allow to have as many slices for different styling if a need be.

Unfortunately, my markup for the first news was in a row div that was closing before the rest of the posts appear in another row so I had to loop twice with foreach. I am sure there is a better way to include the opening and closing divs to avoid double/tripple etc. looping but as far as the result are not more than 6, I am not that worried about slowing the page down...

Share this post


Link to post
Share on other sites
3 hours ago, MilenKo said:

I was looking for a way to style some results of a selector differently than others

If it's just styling, you should first try a CSS-only solution. You can do a lot with just :nth-child or flexbox.

  • Like 1

Share this post


Link to post
Share on other sites

Thanks @dragan will try your approach to see how would that fit, however it is not just styling but the markup is different where the first 2 news are required to have a large image with some intro text, author, date, likes etc. where the next 4 are just title and date of posting.

That is why initially I thought to "slice" the array but it did not work properly so with $a->slice it did the trick. I will see how to serve the posts with a single foreach to avoid duplication, however the classes of divs are different, some javas are included in the no-image divs and some data handling. Not sure if I add a variable for the class, one for the javas and one for data- values to include in the div which one would be faster since I am looping once through 2 results and once through 4 others.

Maybe I could try using modulus operator or other approach as well ?

Share this post


Link to post
Share on other sites

Well I initially tried with the good old counter approach but things got messed up a bit because of the differences in the markup of large image post and others. Will revise the code and see how to include the opening and closing divs properly. Here is the markup I am working with:

Spoiler

<div class="row">

	<!-- Large image post x 2 -->
	<div class="news-block col-lg-4 col-md-6 col-sm-12 wow fadeInUp animated" style="visibility: visible; animation-name: fadeInUp;">
		<div class="inner-box">
			<div class="image-box">
				<figure class="image"><a href="#"><img src="images/resource/news-1.jpg" alt=""></a></figure>
			</div>
			<div class="lower-content">
				<div class="date">26 Aug. 2018</div>
				<h5><a href="blog-detail.html">Mac Keychain Bug Could Be Big Problem For Apple</a></h5>
				<div class="text">Fed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt ...</div>
				<div class="link-box"><a href="blog-detail.html">Read more</a></div>
			</div>
		</div>
	</div>


	<!-- News Block -->
	<div class="news-list col-lg-4 col-md-12 col-sm-12 wow fadeInUp animated" data-wow-delay="800ms" style="visibility: visible; animation-delay: 800ms; animation-name: fadeInUp;">
		<div class="inner-box">
		
			<!-- List Item x 4 -->
			<div class="list-item">
				<h5><a href="blog-detail.html">Nanotechnology immersion along the information.</a></h5>
				<span class="date">Aug 26 2018</span>
			</div>

		</div>
	</div>
</div>

 

Where Large image post shows twice and List Item show 4 times 😉

Share this post


Link to post
Share on other sites
9 minutes ago, MilenKo said:

<div class="news-block col-lg-4 col-md-6 col-sm-12 wow fadeInUp animated"

<div class="news-list col-lg-4 col-md-12 col-sm-12 wow fadeInUp animated" data-wow-delay="800ms"

I like the developer satisfacion coming through these lines 🙂 

  • Like 1
  • Haha 1

Share this post


Link to post
Share on other sites

@tpr Tell me about it 🙂 Just because of the div opening markup I was crushing my head for some time before I "split" the selector in two and then applied the every foreach inside of every div 😉 This could all goe to the CSS but hey - different people, different taste 🙂

Share this post


Link to post
Share on other sites

Guess you could be clever with modulus and some dynamic class names etc. Or, just go for two loops and call it a day. I did something before and tried to be uber clever about it, turns out it's not so clever when you go back and have to waste time working out how it works.

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.

Guest
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.

  • Similar Content

    • By Mithlesh
      Changing it to null
    • By Mithlesh
      Hi, I have one URL - writerrelocations.com/contact-now/

      I have one issue where my header Image is appearing again after the contact form, for your reference:



      I have checked my processwire template section where have not added any Image field besides Header Image, attaching the same for the reference:




      PLEASE help me to get rid of the image below contact form

      Waiting for the swift response!

      Thanks
       
    • By Liam88
      Hi all,
      Quick question as I haven't found anything from my Googling. 
      I have a blog on the site which utilises pagination. On the standard blog page I have a custom header which has featured posts.
      Below that I then have recent posts like mosts blogs.
      Now if i click to page two or three I want the header to disappear and just show a continuation of the standard posts.
      I'm not sure how to go about this so any direction would be helpful.
      Thanks
    • By Violet
      Here I'm introducing FlipFall Magazine, our multi-topic blog. It used to run on Wordpress but we recently switched it to ProcessWire. This was done the usual way we do it when converting our sites: install ProcessWire in a subfolder of the original Wordpress site under a hard-to-guess name, set up the new site there, then move content over manually, inspecting and updating each article as needed. After the ProcessWire site was ready, when we un-installed the Wordpress one and moved the ProcessWire site up one level to the document root, and... done.
      We used the W3CSS framework because it handles the responsive breakpoints so well (no extra work for us 😉), and it tends to default to a clean modern look.
      We wanted full control over the back end of the site and do customized things without having to hire a developer.  As FlipFall has grown, the ability to have in-house back-end control has become even more important.
      Case example: Ad partners - we now can quite easily, if we wish, place different ads on different topics on this blog at a moment's notice - no need to hire a developer. Changes like this can be implemented in-house right away. The fact that we can easily incorporate this sort of thing is really nice when we're talking with potential ad partners.
      Helpful features of ProcessWire during this experience:
      The ability to export and import fields in PW was key here. We had a few other article-style sites I had done in PW recently, so having the same types of templates was very helpful. We were able to export fields and templates from our existing sites and import into FlipFall as a starting base point. No need to re-invent the wheel here! Another helpful ability of PW was when we were dealing with the categories. We built the site without category templates (but with the category page field), then added the templates in later as needed - no disruption. In other words, a template-less page field worked perfectly for the categories until we needed the template, then we just created the template. Not every feature of the site needs to be thought out in absolute full beforehand, some can be added in later as needed. Very extensible and convenient. Internal links within blog posts worked well using the page select option in the link button on the editor. When moving out of staging folder and into document root, the links auto-updated, which was nice. Creating new articles is a breeze, because under PW our fields are now customized for our needs: we created all of the fields we need and none of the ones we don't. Again, this is unlike most blogging CMS's, where they try to guess what you want (and usually get it wrong). Even for people who are solely doing blogs/article sites, I feel that ProcessWire is a much better option than most blog-specific platforms, because of PW's flexibility.  The only thing I miss about Wordpress is the ability to auto-schedule post publication, which for the serious blogger is important. For example, there were some occasions on some of our other blogs where we needed to schedule posts to auto-publish at 3:01am Eastern Time to allow a time-sensitive post to come out as early in time of day as possible on publication date (3:01 am US Eastern time ensures it's that same day 12:01 am on Pacific time). We were delighted to see that ProcessWire is much, much lighter on resources of the hosting environment than the same site on Wordpress - we could see this empirically on our web hosting stats before and after the switch.
    • By NorbertH
      As we are building some webapplications with the PW backend , having those really big spacings between all field elements in forms and everywhere is not too practical. 
      UI Kit already has less spacings between all elements than Bootstrap for example , but i am looking fore a more condensed BE Theme.  Maybe someone already made something like that?
×
×
  • Create New...