Skip to content

Instantly share code, notes, and snippets.

@vojtech-dobes
Created September 10, 2011 00:37
Show Gist options
  • Save vojtech-dobes/1207719 to your computer and use it in GitHub Desktop.
Save vojtech-dobes/1207719 to your computer and use it in GitHub Desktop.
Latte helpers for HTML 5 data-attributes
{* with helper *}
<div id="with-data" data-example="{[a => b]|data}"></div>
{* with macro *}
<div id="with-data" n:data="example, [a => b]"></div>
<script>
var data = parseDataJson($('#with-data'), 'example');
// => data == {a: 'b'}
</script>
<?php
$template->registerHelper('data', function ($data) {
return preg_replace('#(?<!\\\\)"([^\\\\\',]*)"#i', "'$1'", preg_replace('#"([a-z0-9]+)":#i', '$1:', json_encode($data)));
});
<?php
function latte_macro_data($name, $data) {
$data = preg_replace('#"([a-z0-9]+)":#i', '$1:', json_encode($data));
return " data-$name=\"" . preg_replace('#(?<!\\\\)"([^\\\\\',]*)"#i', "'$1'", $data) . '"';
}
LatteMacros::$defaultMacros['@data'] = '<?php echo latte_macro_data(%%); ?>';
<?php
public function templatePrepareFilters($template)
{
$latte = new Nette\Latte\Engine;
$macroSet = new Nette\Latte\Macros\MacroSet($latte->parser);
$macroSet->addMacro('@data', function ($node, $writer) {
return $writer->write("echo ' data-' . %node.word . '=\"' . %escape(\$presenter->formatData(%node.array)) . '\"'");
});
$template->registerFilter($latte);
}
public function formatData($data)
{
return preg_replace('#(?<!\\\\)"([^\\\\\',]*)"#i', "'$1'", preg_replace('#"([a-z0-9]+)":#i', '$1:', json_encode(array_shift($data))));
}
var parseDataJson = function (el, name) {
return eval('[' + (el.getAttribute('data-' + name) || '') + ']')[0];
};
@vojtech-dobes
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment