Last active
October 4, 2018 07:52
-
-
Save pepebe/28082343f674cc7b56ba51c337003bda to your computer and use it in GitHub Desktop.
Responsive bootstrap tables for modx - Wraps tables into a div.table-responsive container and adds a custom class to the table tag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| responsive-tables.php for modx | |
| Wraps tables into a div.table-responsive container and adds a custom class to the table tag | |
| This technique is used by bootstrap 3.3.7 and 4.1: | |
| http://getbootstrap.com/docs/4.1/content/tables/#responsive-tables | |
| Turns: | |
| <table>...</table> | |
| Into: | |
| <div class="table-responsive"> | |
| <table class="table table-striped table-bordered">...</table> | |
| </div> | |
| Use as snippet or output filter | |
| 2do: Adding a don't touch class to a table prevents execution of this script for this table | |
| */ | |
| $html = $input; | |
| $divClass = !empty($divClass) ? $divClass : "table-responsive"; | |
| $tableClass = !empty($tableClass) ? $tableClass : "table table-striped table-bordered"; | |
| $dom = new DOMDocument(); | |
| $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); | |
| //Create new wrapper div | |
| $new_div = $dom->createElement('div'); | |
| $new_div->setAttribute('class',$divClass); | |
| //Find all tables | |
| $tables = $dom->getElementsByTagName('table'); | |
| //Iterate through all tables | |
| foreach ($tables AS $table) { | |
| $oldClass = $table->getAttribute('class'); | |
| if($oldClass == $tableClass) {} | |
| else { | |
| $table->setAttribute('class',$tableClass); | |
| //Clone our created div | |
| $new_div_clone = $new_div->cloneNode(); | |
| //Replace table with this wrapper div | |
| $table->parentNode->replaceChild($new_div_clone,$table); | |
| //Append this image to wrapper div | |
| $new_div_clone->appendChild($table); | |
| } | |
| } | |
| $html = $dom->saveHTML(); | |
| return $html; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment