Jump to content

Writing reusable markup generation functions


MoritzLost
 Share

Recommended Posts

Writing reusable markup generation functions

Hello there, I've been working with ProcessWire for a while now, and I've been writing some helper functions to generate markup and reduce the amount of repetitive code in my templates. In this tutorial I want to explain how to write small, reusable functions and combine them to accomplish bigger tasks. Note that this is the follow-up to my last post, Building a reusable function to generate responsive images. In that tutorial, I demonstrated a pretty large function that generates multiple image variations for responsive images, as well as the corresponding markup. In this post, I'll split this function into multiple smaller functions that can be utilized for other purposes as well. This will be more beginner-orientated than the last one, I hope there's some interest in this anyway ?

Note that for my purposes, I prefer to have those functions as static methods on a namespaced object, so the following code examples will be placed in a simple Html class. However, you can use those as normal functions just as well.

class Html {
	// code goes here
}

Edit: Those functions use some syntax exclusive to PHP 7.1 and above, they won't work in PHP 7.0 and lower. Thanks for @Robin S for pointing that out.

Seperation of concerns

To split up the original function, we need to analyze all the individual tasks it performs:

  • Generate several image variations in different sizes.
  • Generate the corresponding srcset attribute markup according to the specification.
  • Generate the sizes attribute markup based on the passed queries.
  • Automatically include the description as the alt attribute.
  • Generate the markup for all attributes (including the ones passed to the function).
  • Generate the markup for the complete img tag.

The first three of those tasks are very specifically concerned with generating responsive images. Generating the alt attribute is relevant to any img tag, not just responsive images. Finally, generating the attributes and HTML markup is relevant to all HTML markup that one wants to generate. Therefore, this is how a hierarchy between those functions could look like.

  • Generate responsive image
    • Generate image markup
      • Generate any HTML tag markup
        • Generate an HTML start tag
          • Generate HTML attributes markup
        • Generate an HTML end tag

Those bullet points are the tasks I want to turn into individual functions, each accepting arguments as general as they can be, facilitating code reuse. I'll start writing those out from the ground up.

Generating attributes markup

HTML attributes are a list of property-value pairs, where the value is wrapped in quotation marks (") and assigned to the property with an equals-sign (=). Each pair is separated by a space. There are also standalone/empty attributes that don't have a value, for example:

<input id="name" class="form-control" disabled>

Since the input format consists of key-value pairs, it makes sense to use an associative array as the argument to the attributes functions.

public static function attributes(
    array $attributes
): string {
    $attr_string = '';
    foreach ($attributes as $attr => $val) {
        $attr_string .= ' ' . $attr . '="' . $val . '"';
    }
	return $attr_string;
}

However, this still needs to support standalone attributes. Those attributes are also known as boolean attributes, since their presence indicates a true value, their absence the opposite. Since all other values in the markup are strings or integers, we can differentiate between those based on the type of the value in the associative array. If it's a boolean, we'll treat it as a standalone attribute and only include it if the value is also true.

public static function attributes(
    array $attributes,
    bool $leading_space = false
): string {
    $attr_string = '';
    foreach ($attributes as $attr => $val) {
        if (is_bool($val)) {
            if ($val) {
                $attr_string .= " $attr";
            }
        } else {
            $attr_string .= ' ' . $attr . '="' . $val . '"';
        }
    }
    if (!$leading_space) {
        $attr_string = ltrim($attr_string, ' ');
    }
    return $attr_string;
}

Of course, this means that if a value in the array is boolean false, this array item will be left out. This is by design, as it allows the caller to use expressions in the array declaration. For example:

echo Html::attributes([
	'id' => 'name',
	'class' => 'form-control',
	'disabled' => $this->isDisabled()
]);

This way, if isDisabled returns true, the disabled attribute will be included, and left out if it doesn't.

Note that I also included a $leading_space argument for convenience.

Generating start tags, end tags and complete HTML elements

The start tag is identified by the element name and the attributes it contains. The end tag only needs a name. Those functions are trivial:

public static function startTag(
    string $element,
    ?array $attributes = []
): string {
    $attribute_string = self::attributes($attributes, true);
    return "<{$element}{$attribute_string}>";
}

public static function endTag(string $element): string
{
    return "</{$element}>";
}

Of course, the startTag function builds on the existing function to generate the attributes. Note that a start tag is identical with a standalone tag (i.e. a void HTML element such as the img tag).

At this point, it's also trivial to write a function that builds a complete element, including start and end tag as well as the enclosed content.

public static function element(
    string $element,
    ?string $content = null,
    array $attributes = [],
    $self_closing = false
): string {
    if ($self_closing) {
        return self::startTag($element, $attributes);
    } else {
        return self::startTag($element, $attributes) . $content . self::endTag($element);
    }
}

Note that while this function does take several arguments, all except the first have reasonable default values, so usually the caller will only have to pass two or three of them. Some examples:

echo Html::startTag('hr'); // <hr>
echo Html::element('a', 'My website', ['href' => 'http://herebedragons.world']); // <a href="http://herebedragons.world">My website</a>

Image tags

Those functions make for a solid foundation to build any type of HTML element markup. Based on the type, the functions can accept more specific arguments to be easier to use. For example, the previous link example could be simplified by writing a link function that accepts a link text and an href value, since those are needed for any link:

public static function link(
    string $url,
    ?string $text = null,
    array $attributes = []
): string {
    // use url as text if no text was passed
    $text = $text ?? $url;
    $attributes['href'] = $url;
    return self::element('a', $text, $attributes);
}

Anyway, for our image markup function, we'll take a Pageimage object as an argument instead, since most images we will use in a ProcessWire template will come from the ProcessWire API. Since all ProcessWire image fields have a description field by default, we can use that description as the alt attribute, which is good practice for accessibility.

public static function image(Pageimage $img, array $attributes = []): string
{
    $attributes['src'] = $img->url();
    // use image description as alt text, unless specified in $attributes
    if (empty($attributes['alt']) && !empty($img->description())) {
        $attributes['alt'] = $img->description();
    }
    return self::selfClosingElement('img', $attributes);
}

Pretty simple. Note that the alt attribute can still be manually overridden by the caller by including it in the $attributes array.

Responsive images

Now, the responsive image function can be shortened by building on this function in turn. Optimally, the three distinct tasks this performs (see above) should be separated into their own functions as well, however in practice I haven't seen much need for this. Also, this post is plenty long already, so ...

public static function imageResponsive(
    Pageimage $img,
    ?int $standard_width = 0,
    ?int $standard_height = 0,
    ?array $attributes = [],
    ?array $sizes_queries = [],
    array $variant_factors = [0.25, 0.5, 0.75, 1, 1.5, 2]
): string {
    // use inherit dimensions of the passed image if standard width/height is empty
    if (empty($standard_width)) {
        $standard_width = $img->width();
    }
    if (empty($standard_height)) {
        $standard_height = $img->height();
    }
    $suffix = 'auto_srcset';

    // if $attributes is null, default to an empty array
    $attributes = $attributes ?? [];

    // get original image for resizing
    $original_image = $img->getOriginal() ?? $img;

    // the default image for the src attribute
    $default_image = $original_image->size(
        $standard_width,
        $standard_height,
        ['upscaling' => false, 'suffix' => $suffix]
    );

    // build the srcset attribute string, and generate the corresponding widths
    $srcset = [];
    foreach ($variant_factors as $factor) {
        // round up, srcset doesn't allow fractions
        $width = ceil($standard_width * $factor);
        $height = ceil($standard_height * $factor);
        // we won't upscale images
        if ($width <= $original_image->width() && $height <= $original_image->height()) {
            $current_image = $original_image->size($width, $height, ['upscaling' => false, 'suffix' => $suffix]);
            $srcset[] = $current_image->url() . " {$width}w";
        }
    }
    $attributes['srcset'] = implode(', ', $srcset);

    // build the sizes attribute string
    if ($sizes_queries) {
        $attributes['sizes'] = implode(', ', $sizes_queries);
    }

    return self::image($default_image, $attributes);
}

See my last post for details. Since then, I made some changed to the function I outlined here (thanks to @horst for pointing out some pitfalls with my approach). Most notably:

  • The generated images now include a prefix so they can be removed by a cleanup script more easily.
  • The function now accepts a width and a height parameter so that the aspect ratio of the generated images is fixed (reasons for this change are explained here). To get the original functionality back, I also wrote two helper functions that takes only a width/height and fill in the missing parameter based on the aspect ratio of the passed image.

The helper functions look like this:

public static function imageResponsiveByWidth(
    Pageimage $img,
    ?int $standard_width = 0,
    ?array $attributes = [],
    ?array $sizes_queries = [],
    array $variant_factors = [0.25, 0.5, 0.75, 1, 1.5, 2]
): string {
    // automatically fill the height parameter based
    // on the aspect ratio of the passed image
    if (empty($standard_width)) {
        $standard_width = $img->width();
    }
    $factor = $img->height() / $img->width();
    $standard_height = ceil($factor * $standard_width);

    return self::imageResponsive(
        $img,
        $standard_width,
        $standard_height,
        $attributes,
        $sizes_queries,
        $variant_factors
    );
}

Conclusion

This approach was born out of necessity, since pure PHP templating makes for some messy code. Of course, another approach would be to use a template engine in the first place. However, I didn't want the overhead of installing Twig or Blades for my smaller projects, so for those small to medium-sized projects, I found some helper functions to generate markup and clean up my code to be a helpful addition.

A small disclaimer, I update those functions pretty frequently while developing with ProcessWire, so it's possible some errors made their way into the versions I posted here that I haven't discovered yet. If you want to use some of the included code in your own projects, make sure to properly test it.

I'm also working on a small library including those and some other helpers I wrote, I'll post a Github link once it's in a usable stage.

So this post got way longer than I intended, I hope that some of you still made your way through it and enjoyed it a bit ? If you see some problems or possible improvements to those methods and the general approach, I'd be happy to hear them!

Complete code for reference


<?php

use \Processwire\Pageimage;

class Html
{

    /**
     * Build a simple element tag with the passed element.
     *
     * @param string $element The element/tag name as a string.
     * @param ?string $content The content of the element (what goes between the tags).
     * @param ?array $attributes Optional attributes for the element.
     * @param boolean $self_closing Whether the element is self-closing (i.e. no end tag). $content is ignored if true.
     * @return string The HTML element markup.
     */
    public static function element(
        string $element,
        ?string $content = null,
        array $attributes = [],
        $self_closing = false
    ): string {
        if ($self_closing) {
            return self::startTag($element, $attributes);
        } else {
            return self::startTag($element, $attributes) . $content . self::endTag($element);
        }
    }

    /**
     * Builds a start tag for an element (or a self-closing/void element).
     *
     * @param string $element
     * @param array $attributes
     * @return string The HTML start tag markup.
     */
    public static function startTag(
        string $element,
        ?array $attributes = []
    ): string {
        $attribute_string = self::attributes($attributes, true);
        return "<{$element}{$attribute_string}>";
    }

    /**
     * Build an end tag for an element.
     *
     * @param string $element The HTML end tag markup.
     * @return void
     */
    public static function endTag(string $element): string
    {
        return "</{$element}>";
    }
	
    /**
     * Build an HTML attribute string from an array of attributes. Attributes set
     * to (bool) true will be included as standalone (no attribute value) and left
     * out if set to (bool) false.
     *
     * @param array $attributes Attributes in attribute => value form.
     * @param bool $leading_space Whether to include a leading space in the attribute string.
     * @return string The attributes as html markup.
     */
    public static function attributes(
        array $attributes,
        bool $leading_space = false
    ): string {
        $attr_string = '';
        foreach ($attributes as $attr => $val) {
            if (is_bool($val)) {
                if ($val) {
                    $attr_string .= " $attr";
                }
            } else {
                $attr_string .= ' ' . $attr . '="' . $val . '"';
            }
        }
        if (!$leading_space) {
            $attr_string = ltrim($attr_string, ' ');
        }
        return $attr_string;
    }

    /**
     * Image Functions.
     */

    /**
     * Build a simple image tag from a Processwire Pageimage object.
     *
     * @param Pageimage $img The image to use.
     * @param array $attributes Optional attributes for the element.
     * @return string
     */
    public static function image(Pageimage $img, array $attributes = []): string
    {
        $attributes['src'] = $img->url();
        // use image description as alt text, unless specified in $attributes
        if (empty($attributes['alt']) && !empty($img->description())) {
            $attributes['alt'] = $img->description();
        }
        return self::selfClosingElement('img', $attributes);
    }

    /**
    * Builds a responsive image element including different resolutions
    * of the passed image and optionally a sizes attribute build from
    * the passed queries.
    *
    * @param Pageimage $img The base image. Must be passed in the largest size available.
    * @param int|null $standard_width The standard width for the generated image. Use NULL to use the inherent size of the passed image.
    * @param int|null $standard_height The standard height for the generated image. Use NULL to use the inherent size of the passed image.
    * @param array|null $attributes Optional array of html attributes.
    * @param array|null $sizes_queries The full queries and sizes for the sizes attribute.
    * @param array|null $variant_factors The multiplication factors for the alternate resolutions.
    * @return string
    */
    public static function imageResponsive(
        Pageimage $img,
        ?int $standard_width = 0,
        ?int $standard_height = 0,
        ?array $attributes = [],
        ?array $sizes_queries = [],
        array $variant_factors = [0.25, 0.5, 0.75, 1, 1.5, 2]
    ): string {
        // use inherit dimensions of the passed image if standard width/height is empty
        if (empty($standard_width)) {
            $standard_width = $img->width();
        }
        if (empty($standard_height)) {
            $standard_height = $img->height();
        }
        $suffix = 'auto_srcset';

        // if $attributes is null, default to an empty array
        $attributes = $attributes ?? [];

        // get original image for resizing
        $original_image = $img->getOriginal() ?? $img;

        // the default image for the src attribute
        $default_image = $original_image->size(
            $standard_width,
            $standard_height,
            ['upscaling' => false, 'suffix' => $suffix]
        );

        // build the srcset attribute string, and generate the corresponding widths
        $srcset = [];
        foreach ($variant_factors as $factor) {
            // round up, srcset doesn't allow fractions
            $width = ceil($standard_width * $factor);
            $height = ceil($standard_height * $factor);
            // we won't upscale images
            if ($width <= $original_image->width() && $height <= $original_image->height()) {
                $current_image = $original_image->size($width, $height, ['upscaling' => false, 'suffix' => $suffix]);
                $srcset[] = $current_image->url() . " {$width}w";
            }
        }
        $attributes['srcset'] = implode(', ', $srcset);

        // build the sizes attribute string
        if ($sizes_queries) {
            $attributes['sizes'] = implode(', ', $sizes_queries);
        }

        return self::image($default_image, $attributes);
    }

    /**
    * Shortcut for the responsiveImage function that only takes a width parameter.
    * Height is automatically generated based on the aspect ratio of the passed image.
    *
    * @param Pageimage $img The base image. Must be passed in the largest size available.
    * @param int|null $standard_width The standard width for this image. Use NULL to use the inherent size of the passed image.
    * @param array|null $attributes Optional array of html attributes.
    * @param array|null $sizes_queries The full queries and sizes for the sizes attribute.
    * @param array|null $variant_factors The multiplication factors for the alternate resolutions.
    * @return string
    */
    public static function imageResponsiveByWidth(
        Pageimage $img,
        ?int $standard_width = 0,
        ?array $attributes = [],
        ?array $sizes_queries = [],
        array $variant_factors = [0.25, 0.5, 0.75, 1, 1.5, 2]
    ): string {
        // automatically fill the height parameter based
        // on the aspect ratio of the passed image
        if (empty($standard_width)) {
            $standard_width = $img->width();
        }
        $factor = $img->height() / $img->width();
        $standard_height = ceil($factor * $standard_width);

        return self::imageResponsive(
            $img,
            $standard_width,
            $standard_height,
            $attributes,
            $sizes_queries,
            $variant_factors
        );
    }

    /**
    * Shortcut for the responsiveImage function that only takes a height parameter.
    * Width is automatically generated based on the aspect ratio of the passed image.
    *
    * @param Pageimage $img The base image. Must be passed in the largest size available.
    * @param int|null $standard_height The standard height for this image. Use NULL to use the inherent size of the passed image.
    * @param array|null $attributes Optional array of html attributes.
    * @param array|null $sizes_queries The full queries and sizes for the sizes attribute.
    * @param array|null $variant_factors The multiplication factors for the alternate resolutions.
    * @return string
    */
    public static function imageResponsiveByHeight(
        Pageimage $img,
        ?int $standard_height = 0,
        ?array $attributes = [],
        ?array $sizes_queries = [],
        array $variant_factors = [0.25, 0.5, 0.75, 1, 1.5, 2]
    ): string {
        // automatically fill the width parameter based
        // on the aspect ratio of the passed image
        if (empty($standard_height)) {
            $standard_height = $img->height();
        }
        $factor = $img->width() / $img->height();
        $standard_width = ceil($factor * $standard_height);

        return self::imageResponsive(
            $img,
            $standard_width,
            $standard_height,
            $attributes,
            $sizes_queries,
            $variant_factors
        );
    }

}

 

Edited by MoritzLost
PHP compatibility notice
  • Like 11
  • Thanks 1
Link to comment
Share on other sites

22 hours ago, Robin S said:

Really great tutorial, thanks!

Might be worth noting that a minimum of PHP 7.1 is required for the code syntax used.

That's correct, I barely think about that anymore since I'm able to write PHP 7.2 at work ^^' Thanks!

11 hours ago, bernhard said:

Very nice tutorial, thx!

I wonder if that would be nice to have as a module. Installable, reusable, one-click-updateable....

But maybe it would be easier to extend available libraries, such as https://doc.nette.org/en/2.4/html-elements

I'm working on that, though at the moment I'm just building it as a generic composer package. Just seems easy since you get to use the composer autoloader ... I haven't found a simple way to autoload classes in a Processwire module, and performance-wise I don't like the idea of including everything on every request.

That nette module is interesting, I actually started building something like that at first, but it turned out to be more overhead than I needed most of the time. Though the nette module seems much simpler than my first approach, so maybe I gave up too quickly ...

How would you include another library such as nette in a Processwire module? Manually or is there a more Processwire-y way to include dependencies?

  • Like 3
Link to comment
Share on other sites

42 minutes ago, MoritzLost said:

How would you include another library such as nette in a Processwire module? Manually or is there a more Processwire-y way to include dependencies?

That's two approaches I did in my modules:

https://gitlab.com/baumrock/RockPdf/blob/master/RockPdf.module.php#L37-38

https://gitlab.com/baumrock/RockForms/blob/master/RockForms.module.php#L63-64

But I have to admit that I don't use all those composer, gulp and whatsoever tools, so there might be better solutions and I'd be happy to see how others do ? 

  • Like 1
Link to comment
Share on other sites

On 10/25/2018 at 9:59 PM, bernhard said:

That's two approaches I did in my modules:

https://gitlab.com/baumrock/RockPdf/blob/master/RockPdf.module.php#L37-38

https://gitlab.com/baumrock/RockForms/blob/master/RockForms.module.php#L63-64

But I have to admit that I don't use all those composer, gulp and whatsoever tools, so there might be better solutions and I'd be happy to see how others do ? 

I see, so you're packing the dependencies alongside the composer autoloader and including the autoloader on a per-module basis. That's certainly self-contained, very good solution for sites that don't use composer. Though it does mean dependencies can't be reused across modules. I guess there's something to be said for both approaches. Maybe I can put out a little module that provides a wrapper through the composer library (once it's published) so it can be installed through the Processwire GUI and called through the Processwire API. First I gotta get around to finishing it though ^^

I have started to use Composer for my latest two Processwire projects; it's a pretty simple setup, I just put the composer.json and vendor folder one directory above the webroot and then include the autoloader in the init.php file. This way it's no overhead at all, I can just use any libraries I want to and don't need to worry about anything else. Of course I have to update the composer dependencies independently from the modules, but that's just a few CLI commands away. Maybe I'll write a short tutorial for that too :)

  • Like 3
Link to comment
Share on other sites

23 hours ago, gmclelland said:

@bernhard I thought /vendor/autoload.php was already loaded by Processwire automatically if it exist?  https://processwire.com/blog/posts/composer-google-calendars-and-processwire/

Maybe you don't need to require it in your modules?

ProcessWire automatically includes the autoloader if it's located at /vendor/autoload.php. If the module is installed manually / through the backend, ProcessWire has no way of knowing about the included autoloader. Likewise, even if you have composer initialized in the root directory, the autoloader has no way of knowing that the dependencies of the module are located in the module's directory. So bernhard just includes the dependencies and the composer autoloader. The included autoload.php generated by Composer just calls spl_autoload_register, which adds the included composer autoloader instance to the autoload queue. This way, the module contains it's own dependencies and autoloader, so it can be installed through the GUI and still benefit from autoloading. Quite a neat solution actually.

Link to comment
Share on other sites

  • 1 month later...

Inspired by this i whipped up something.

class element
{
	protected $element = null;
	protected $attributes = [];

	function __construct( string $element )
	{
		$this->element = $element;
	}


	public function attribute(string $key, ?string $value = null, ?bool $replace = false)
	{

		if ( empty($value) ) return empty( $attributes[$key] ) ? null : $attributes[$key];


		if ($replace or empty($attributes[$key])) {
			$this->attributes[$key] = $value;
		} else {
			$this->attributes[$key] .= $value;
		}

		return $this;
	}

	public function attributes(array $items, ?bool $replace = false)
	{
		foreach ($items as $key => $value) {
			self::attribute($key, $value, $replace);
		}

		return $this;

	}

	public function class(?string $value = null, ?bool $replace = false) { return self::attribute('class', $value, $replace); }
	public function id   (?string $value = null, ?bool $replace = false) { return self::attribute('id',    $value, $replace); }


	public function content( $content )
	{

		$content = $this->start().$content.$this->end();

		return $content;
	}

	public function start()
	{
		$attribute_string = self::generate($this->attributes, true);
		$element = $this->element;

		$content =  "<{$element}{$attribute_string}>";

		return $content;
	}

	public function end()
	{
		$element = $this->element;
		$content = "</{$element}>";

		return $content;
	}

	public function closing()
	{
		$attribute_string = self::generate($this->attributes, true);
		$element = $this->element;
		$content = "<{$element}{$attribute_string} />";

		return $content;
	}




	protected function generate(
		array $attributes,
		bool $leading_space = false
	): string {
		$attr_string = '';
		foreach ($attributes as $attr => $val) {
			if (is_bool($val)) {
				if ($val) {
					$attr_string .= " $attr";
				}
			} else {
				$attr_string .= ' ' . $attr . '="' . $val . '"';
			}
		}
		if (!$leading_space) {
			$attr_string = ltrim($attr_string, ' ');
		}
		return $attr_string;
	}
}

function element( string $element )
{
	return new element( $element );
}

 

I haven't tested it much but should be usable.

 

// example usage -- not tested!

$navelement = element('li')->class('navitem');
$navitems = pages('/')->and(pages('/')->children())

echo element('ul')->content(
	$navitems->each( $navelement->content('{title}')
);

// or
echo element('ul')->start();
foreach($navitems as $item) {
	echo $navelement->content($item->title);
}
echo element('ul')->end();

 

Edited by derixithy
I'm a total noob at oop, now it's (probably) working.
  • Like 1
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

×
×
  • Create New...