modifier.add_styles.php
1 <?php
2 /**
3  * wCMF - wemove Content Management Framework
4  * Copyright (C) 2005-2020 wemove digital solutions GmbH
5  *
6  * Licensed under the terms of the MIT License.
7  *
8  * See the LICENSE file distributed with this work for
9  * additional information.
10  */
12 
13 /**
14  * Add classes to elements in an html string
15  *
16  * Example:
17  * @code
18  * {$html|add_styles:['p' => 'contact lh-title f4 f3-m f2_3-l near-black db pb2 l','a' => 'link near-black']}
19  * @endcode
20  *
21  * @param $string The html string
22  * @param $styles Map with element names as keys and string with class names as values
23  * @param $onlyIfUnstyled Boolean indicating whether to add styles only, if the element has no classes or always (default: true)
24  * @return String
25  */
26 function smarty_modifier_add_styles($html, $styles, $onlyIfUnstyled=true) {
27  return strlen($html) > 0 ? DOMUtils::processHtml($html, function(\DOMDocument $doc) use ($styles, $onlyIfUnstyled) {
28  $xpath = new \DOMXpath($doc);
29  foreach ($styles as $name => $classes) {
30  $elements = $xpath->query("//".$name);
31  foreach ($elements as $element) {
32  $classAttr = trim($element->getAttribute("class"));
33  if (strlen($classAttr) == 0 || !$onlyIfUnstyled) {
34  $existingClasses = explode(" ", $element->getAttribute("class"));
35  $allClasses = array_unique(array_merge($existingClasses, explode(" ", $classes)));
36  $element->setAttribute("class", join(" ", $allClasses));
37  }
38  }
39  }
40  }) : '';
41 }
42 ?>