Jump to content

Targeting foreach statements with CSS?


PhotoWebMax
 Share

Recommended Posts

Another newby question if I may?

Say I have a news posting system using the following:

<?php
		$newsItems = $pages->find("template=widgetNews");
		foreach($newsItems as $newsItem) { ?>
		  <h3><?php echo $newsItem->title; ?></h3>
		  <h4><?php echo $newsItem->newsDate; ?></h4>
		  <?php echo $newsItem->newsSummary; ?>
		  <?php 
		}

		?>

What is the best way of attaching some CSS class styling to each post as a whole? 

Thanks!

Link to comment
Share on other sites

Something like this :)
 

<?php
$newsItems = $pages->find("template=widgetNews");
foreach($newsItems as $newsItem) { ?>
    <article class="newsItem">
        <h3><?php echo $newsItem->title; ?></h3>
        <h4><?php echo $newsItem->newsDate; ?></h4>
        <?php echo $newsItem->newsSummary; ?>
    </article>
<?php 
}
?>

Wrap each post's content in another tag which you can style separately. Here I used the article tag, but a div would work just as well.

  • Like 5
Link to comment
Share on other sites

Just to add to Craig's post, if you needed to style each item differently for any reason, you could do something like this:

<?php
$newsItems = $pages->find("template=widgetNews");
$i = 1;
foreach($newsItems as $newsItem) { ?>
    <article class="newsItem newsItem<?php echo $i ?>">
        <h3><?php echo $newsItem->title; ?></h3>
        <h4><?php echo $newsItem->newsDate; ?></h4>
        <?php echo $newsItem->newsSummary; ?>
    </article>
<?php 
 $i++;
}
?>

That would give you the shared newsItem class as well as a unique newsItem# class with the number of the iteration (i.e. newsItem1, newsItem2, newsItem3). Similarly, you could use the page's name instead of a number by tacking that on to the end of the class.

  • Like 3
Link to comment
Share on other sites

Thanks Everfreecreative,

That is good to know. For the moment I am using the nth-child(even) selector to do different things. 

I have not built sites in quite some time but I am back in the swim of things now: several site projects on the go. Coding markup, CSS, Php (the tiny amount I know) and all things ProcessWire is really fun again. The more I play with PW the more I like it...

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
 Share

  • Recently Browsing   0 members

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