Skip to content

Instantly share code, notes, and snippets.

@dnaber-de
Created May 7, 2012 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dnaber-de/2627721 to your computer and use it in GitHub Desktop.
Save dnaber-de/2627721 to your computer and use it in GitHub Desktop.
A template helper to print HTML-Classes to each element in a loop which matches the CSS nth-child syntax
<?php
declare( encoding='UTF-8' );
/**
* A template helper to print class-names
* to eacht element, matches the equation xn+y
*
* @author David Naber <kontakt@dnaber.de>
*/
class Nth_Child_Class {
/**
* the index
*
* @var int
*/
protected $i = 0;
/**
* equation parts
*
* @var string
*/
protected $equ = array();
/**
* the class to print
*
* @var string
*/
protected $class_name = '';
/**
* constructor
*
* @param string $equ ( has to match the synax xn+y | x,y ∈ ℤ )
* @return MP_Loop_Count
*/
public function __construct( $equ = '', $class_name = 'border' ) {
$this->class_name = $class_name;
$this->equ[ 'x' ] = 1;
$this->equ[ 'y' ] = 0;
$this->equ[ 'c' ] = 0;
if ( ! empty ( $equ ) && is_string( $equ ) ) {
$matches = array();
if ( preg_match( '~^(-?\d*)n?([+|-]\s?\d+)?$~', $equ, $matches ) ) {
if ( ! empty( $matches[ 1 ] ) ) {
if ( '-' === $matches[ 1 ] )
$this->equ[ 'x' ] = -1;
else
$this->equ[ 'x' ] = ( int ) $matches[ 1 ];
}
if ( ! empty( $matches[ 2 ] ) )
$this->equ[ 'y' ] = ( int ) $matches[ 2 ];
if ( FALSE === strpos( $matches[ 0 ], 'n' ) )
$this->equ[ 'c' ] = $this->equ[ 'x' ];
}
}
}
/**
* get the class on every cycle that matches the equation
*
* @param string $class_name (optional)
* @return string
*/
public function get_class( $class_name = '' ) {
if ( empty( $class_name ) )
$class_name = $this->class_name;
$p = -1;
$this->i ++;
if ( 0 < $this->equ[ 'c' ] ) {
if ( $this->i === $this->equ[ 'c' ] )
return $class_name;
return '';
}
$p = ( $this->i - $this->equ[ 'y' ] ) / $this->equ[ 'x' ] ;
if ( is_int( $p ) && $p > -1 )
return $class_name;
return '';
}
/**
* print the class
*
* @param string $class (Optional)
* @return void
*/
public function print_class( $class_name = '' ) {
echo $this->get_class( $class_name );
}
}
<?php
include './class-Nth_Child_Class.php';
$nth_child = new Nth_Child_Class( 'n+4' );
?><!DOCTYPE html>
<html lang="de" dir="ltr">
<meta charset="utf-8">
<title>Get Classes instead of nth-child-selector</title>
<style>
li:nth-child( n+4 ){
background: green;
}
</style>
<ul>
<?php for ( $i = 1; $i <= 20; $i++ ) : ?>
<li>
<?php $nth_child->print_class( "I'm green" ); ?>
</li>
<?php endfor; ?>
</ul>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment