https://github.com/dantleech/object-renderer
Render any object with tempate make pretty
https://github.com/dantleech/object-renderer
Last synced: 5 months ago
JSON representation
Render any object with tempate make pretty
- Host: GitHub
- URL: https://github.com/dantleech/object-renderer
- Owner: dantleech
- License: mit
- Created: 2020-04-22T22:11:08.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2024-06-02T10:03:54.000Z (about 2 years ago)
- Last Synced: 2025-04-14T01:12:40.081Z (about 1 year ago)
- Language: PHP
- Homepage:
- Size: 42 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
Object Renderer
===============
[](https://travis-ci.org/dantleech/indexer-extension)
Render / pretty print objects using Twig templates.
- Templates are selected based on the FQN.
- Templates are fallback based on class hierarchy.
- Templates can render objects.
This library, or ones like it, could be suitable for:
- Pretty print `ReflectionClass` and friends, (e.g. printing formatted
documentation in a language server).
- Building a CMS based on _objects_.
- Other things.
Rendering an Object
-------------------
Create a renderer and render an object:
```php
$renderer = ObjectRendererBuilder::create()
->addTemplatePath('example/path')
->build();
$renderer->render(new \stdClass());
```
Will throw an exception:
```
Could not render object "stdClass" using templates "stdClass.twig"',
```
You can guess what you need to do, create `stdClass.twig` in the path given in
the builder:
```
# stdClass.twig
Hello I am a stdClass
```
Object Properties and Recursive Rendering
-----------------------------------------
The object is available as `object` in the template.
If the object contains other objects, you can recurisvely render them
by calling `render(object.anotherObject)`.
Ancestor Class Template Resolution
----------------------------------
If a template for a given object's class is not found. The renderer will
try and locate a template for each of the parent classes.
DOMDocument Example
-------------------
```
{# DOMDocument.twig #}
DOMDocument:
{% for node in object.childNodes %}
- {{ render(node) }}
{%- endfor -%}
```
```
{# DOMElement.twig #}
Element: "{{ object.nodeName }}"
{% for attribute in object.attributes %}
{{ render(attribute) }}
{%- endfor -%}
```
```
{# DOMAttr.twig #}
{{ object.name }}: {{ object.value }}
```
Render them like:
```php
$dom = new DOMDocument();
$child1 = $dom->createElement('child-1');
$child1->setAttribute('foo', 'bar');
$dom->appendChild($child1);
$child2 = $dom->createElement('child-2');
$child2->setAttribute('bar', 'foo');
$dom->appendChild($child2);
$renderer = ObjectRendererBuilder::create()
->addTemplatePath('example/path')
->build();
$renderer->render($dom);
```
Should return something like:
```
DOMDocument:
- Element: "child-1"
foo: bar
- Element: "child-2"
bar: foo
```