Skip to content

Instantly share code, notes, and snippets.

@geekbrit
Last active June 2, 2018 17:48
Show Gist options
  • Save geekbrit/f871e56f7c3befe319ec70deec9d5f95 to your computer and use it in GitHub Desktop.
Save geekbrit/f871e56f7c3befe319ec70deec9d5f95 to your computer and use it in GitHub Desktop.
This gist takes json generated by yakovlevga/brickyeditor and a set of templates in an html file, and munges everything together to create a static html (or twig) file. Follows containers down to correctly fill out the container content.
<?php
// method from a CMS object
function build_page_twig(){
libxml_use_internal_errors(TRUE); // this avoids errors thrown on HTML5 tags
//
// this section is cms-specific, could just pass in the json file name
//
$jsonfile = $this->config->root.'/content/'.$this->config->page.".json";
if( file_exists( $jsonfile ) ){
$pageblocks = json_decode( file_get_contents( $jsonfile ) );
} else {
$this->push_error( "No page data for ".$this->config->page );
return;
}
$templates = [];
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents('ny5/blocks/templateblocks.twig'));
$divs = $doc->getElementsByTagName('div');
foreach( $divs as $div ){
if( $div->getAttribute('class') == 'bre-template' ){
$templatename = $div->getAttribute('data-name');
$templates[$templatename] = new DomDocument;
$templates[$templatename]->appendChild($templates[$templatename]->importNode( $div, true ));
}
}
foreach( $pageblocks as $block ){
$dom = $templates[ $block->template ];
$this->expandTemplate( $dom, $templates, $block );
}
echo $dom->saveHTML(); // change this line to save munged html off to a static file for the page
}
function generate_nodes( $dom ){
foreach( $dom->childNodes as $node ){
yield( $node );
if( $node->hasChildNodes() ){
yield from $this->generate_nodes( $node );
}
}
}
function expandTemplate( &$root, $templates, $block ){
foreach( $this->generate_nodes($root) as $node ){
if( 'DOMElement' != get_class( $node ) ){
continue;
}
$rawfield = str_replace("'",'"',$node->getAttribute('data-bre-field'));
if( "" !== $rawfield ){
$templatefield = json_decode( $rawfield );
foreach( $block->fields as $blockfield ){
if( $templatefield->name == $blockfield->name ){
switch( $templatefield->type ){
case 'img': // img not yet tested
case 'html':
$node->nodeValue = $blockfield->html;
break;
case 'container':
$contained_blocks = $blockfield->blocks;
foreach( $contained_blocks as $cblock ){
$contained_dom = $templates[$cblock->template];
$this->expandTemplate($contained_dom, $templates, $cblock);
$newnode = $root->importNode($contained_dom->getElementsByTagName('div')->item(0), true);
$node->appendChild( $newnode );
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment