ryan

Hanna Code

335 posts in this topic

Easily insert any complex HTML, Javascript or PHP output in your ProcessWire content by creating your own Hanna code tags.
This module is based loosely on the WordPress Hana Code Insert plugin.
 
post-2-0-11674600-1370199246_thumb.png
 
post-2-0-50116800-1370199239_thumb.png
 
A Hanna code tag looks like [[hello_world]]. A Hanna code tag with attributes looks like [[hello_world foo=bar" bar="foo]] using HTML style attributes or [[hello_world foo=bar, bar=foo]] using ProcessWire selector style attributes. After installing the module, you define your Hanna codes in Setup > Hanna Code.
 
These Hanna codes that you define can then be entered within your body copy (or other text where you allow) and they will be replaced with the values defined or generated by your Hanna code. A common use case is to embed scripts or other bits of HTML or codes that would usually be stripped out by an editor like TinyMCE. However, Hanna codes can be more than just static snippets--they can be dynamic PHP or Javascript that outputs different things according to the request. PHP-based Hanna codes have access to the entire ProcessWire API.
 
Hanna code accepts named attributes in the tag that can be passed as variables to PHP and Javascript Hanna codes. These attributes can be specified either in HTML attribute format or ProcessWire selector format. In either case, quotes should be used around the attribute value when the value contains whitespace or a comma.
 
How to install
  • Place the module files in /site/modules/TextformatterHannaCode/
  • In your admin, click Modules > Check for new modules
  • Click install for TextformatterHannaCode
  • Now to go Setup > Fields and locate the Textarea field(s) that you want to use Hanna codes with ("body" for instance). 
  • When editing the field, click the details tab, and select "Hanna Code" as the Textformatter. Save.
  • Now go to Setup > Hanna Code and start defining your Hanna Codes! You may want to use one of the examples from this document to get started.
Tag format
 
Below is a Hanna code tag named hello_world with no attributes. If you pasted this into your body copy, you would get whatever the replacement value is that you defined.
[[hello_world]]
Below is a Hanna code tag named hello_world being passed attributes of foo, bar and foobar. If this were a PHP-based Hanna code, it would receive the variables $foo, $bar and $foobar:
[[hello_world foo="bar" bar="foo" foobar="foo bar"]]
Below is the same Hanna code tag as above, but with attributes more like ProcessWire selectors. You can use whatever format you prefer. Just note that unlike regular ProcessWire selectors, quotes (single or double) are required around any value that has whitespace.
[[hello_world, foo=bar, bar=foo, foobar="foo bar"]] 
How to use
 
Please make sure that you have completed the How to install section first. Then in your admin, go to Setup > Hanna Codes.
 
Each Hanna code that you add has a type of either: Text/HTML, Javascript or PHP. The Text/HTML type is literally self explanatory in that your [[custom-tag]] is replaced with exactly the text you paste in. Anywhere that you type your [[custom-tag]] in your body copy will be replaced with exactly the static text you defined.
 
More power opens up with the Javascript and/or PHP types of codes. These codes execute at runtime and thus can contain specific logic to produce different results. In fact, PHP Hanna codes have access to the entire ProcessWire API and are executed in the same manner as template files. Your PHP-based Hanna code should simply "echo" or "print" the replacement value.
 
PHP example
  • Create a new Hanna code with the name "children".
  • Select "PHP" as the type.
  • Paste in the following for the code:
foreach($page->children as $child) {
  echo "<p><a href='$child->url'>$child->title</a>";
}
  • Now go and edit a page that has children. In the body copy, enter [[children]] in the place where you want the output to appear.
  • View the page, and you should see the rendered list of links to children.
PHP example, part 2
 
Now lets take the above example further...
  • Go back and edit your "children" Hanna code, as we are going to modify it to respond to a "parent" attribute. Change the code to this:
if(isset($parent)) {
  // If $parent is an ID or path, lets convert it to a Page
  $parent = $pages->get($parent);
} else {
  // otherwise lets assume the current page is the parent
  $parent = $page; 
}

foreach($parent->children as $child) {
  echo "<p><a href='$child->url'>$child->title</a>";
}
  • Go back and edit the page where you previously inserted the [[children]] tag, and change it to: [[children, parent=1]] (specifying the homepage) or [[children, parent=/path/to/some/parent/]] if you want to try something else.
  • View the page and you should now see it showing the children of the homepage (or of another parent you specified).
Please see the Javascript and PHP usage notes on the Hanna code entry screen.
 
Security
 
There are major security implications with a tool that will let you enter unfiltered text and code from your web browser. As a result, Hanna codes are meant for definition only by superusers and we recommend keeping it that way.
 
Download
 
Download the Hanna Code module from the ProcessWire modules page or from GitHub
33 people like this

Share this post


Link to post
Share on other sites

Just a note to all MODx'ers - I think this is a nice way to transfer some snippets/chunks to ProcessWire as well if people want to go down that route and have some they used to use in body text. Obviously it's not quite the same thing (potentially more powerful depending on your needs), but anything that helps make a transition easier is good in my book :)

Very useful, powerful module ryan!

3 people like this

Share this post


Link to post
Share on other sites

Wow! Great module, Ryan.

Gonna create a bunch of snippets for quick prototyping and trying things. Expect a new wave of MODx'ers on the forum. These folks love using code snippents the way Hanna Code allows it!

Edit: Pete, we had almost the same thought!

1 person likes this

Share this post


Link to post
Share on other sites

Wow! Nice one; you've been busy!

Yes, there have been two or three questions from MODx'ers in the forums about something like this - the ability to randomly, directly call snippets, chunks and TVs within the body field/area in TinyMCE. Previously they've been pointed to shortcodes and tag parser. Hanna is certainly more powerful and would solve this issue easily.

I can't wait to see the creative ways people use this :rolleyes: .

Thx for the module!

2 people like this

Share this post


Link to post
Share on other sites

Ryan,

This is great — thank you!

Quite a lot happening around here for a Sunday.

:)

2 people like this

Share this post


Link to post
Share on other sites

Nice addition to the growing collection of very useful modules!

1 person likes this

Share this post


Link to post
Share on other sites

Looks like a very useful module, thanks for sharing it Ryan.

I just tried to install it using ModulesManager, and I can't install it right after downloading as it requires Textformatter module to be installed.

TemplateFile: Module ProcessHannaCode requires: TextformatterHannaCode

#0 [internal function]: Modules->___install('ProcessHannaCod...')...

Couldn't it be installed when installing the process module?

Edit: When I create a new hanna code and not enter a tag name and save I get an error and can't see the form.

1 person likes this

Share this post


Link to post
Share on other sites

This looks brilliant Ryan, thank you! There are parallels with a nice aspect of Textpattern here also, TXP 'Forms' (snippets). Brill! ^_^

1 person likes this

Share this post


Link to post
Share on other sites

Looks like a very useful module, thanks for sharing it Ryan.

I just tried to install it using ModulesManager, and I can't install it right after downloading as it requires Textformatter module to be installed.

TemplateFile: Module ProcessHannaCode requires: TextformatterHannaCode

#0 [internal function]: Modules->___install('ProcessHannaCod...')...

Couldn't it be installed when installing the process module?

Edit: When I create a new hanna code and not enter a tag name and save I get an error and can't see the form.

Works fine if you use default Module manager (PW's). You can only install via TextformatterHannaCode actually. Summary says this "Also Installs - ProcessHannaCode". The install button for  ProcessHannaCode is greyed out with the message "Requires - TextformatterHannaCode". ProcessHannaCode auto installs. Maybe something with ModulesManager?

@Ryan: The TextformatterHannaCode and ProcessHannaCode have the same name - "Hanna Code" in PW module manager. This can be confusing :) (but not a big deal).

post-894-0-28482800-1370266185_thumb.png

Share this post


Link to post
Share on other sites

@kongodo, but I don't use Modules page anymore :D I didn't see that the Textformatter is the mother module. At the end it got installed but it's confusing.

Of course it has to do with ModulesManager and the nature of the modules. Modules Manager doesn't know what modules are there and how to install. It takes the module "class name" that is entered on modules.processwire.com to create folder and installs the main module. It's all information I got from modules.processwire.com and there's no manifest, dependencies or lifecycle informations to modules in PW (which IMO is requires rather sooner than later)

For some reason it seems now Ryan has changed the module class name to "TextformatterHannaCode", and this should work better now. Though changing those settings "class name" is dangerous once the module is installed via ModulesManager, because there's actually two different folders for the same module.

Share this post


Link to post
Share on other sites
I just tried to install it using ModulesManager, and I can't install it right after downloading as it requires Textformatter module to be installed.

Sorry about that, I went back and forth on the name a couple times and ultimately entered the wrong class name in the modules directory. It should have been TextformatterHannaCode, not ProcessHannaCode. I have corrected that.

Edit: When I create a new hanna code and not enter a tag name and save I get an error and can't see the form.

I was throwing an exception when I shouldn't have. I'm pushing a correction for this. 

 The TextformatterHannaCode and ProcessHannaCode have the same name - "Hanna Code" in PW module manager. This can be confusing :) (but not a big deal).

Technically they are part of the same program "Hanna Code", even if that program has two modules. But I know what you mean. I'm adding "(Process)" to the Process one, just so that the two next to each other can be differentiated. 

Also, one more section I just added to the README:

Using Hanna Code from the API
 
If you want to populate Hanna Code from the API, you can do so using the render() method, like this:
$hanna = $modules->get('TextformatterHannaCode'); 
$page->body = $hanna->render($page->body); 
8 people like this

Share this post


Link to post
Share on other sites

Just posted version 0.0.2 that addresses the items above. It also adds an option that lets you specify whether the immediate surrounding HTML tag should be replaced with your Hanna Code output or not. For instance, if your [[hello-world]] Hanna Code output is "Hello World" and is applied to the body copy containing "<p>[[hello-world]]</p>" then you probably don't want it to replace the surrounding <p> tags. Whereas if your Hanna Code outputs block level elements like "<ul><li>Hello World</li></ul>" then you probably do want it to replace the surrounding <p> tags, otherwise you'd end up with some invalid markup like: <p><ul><li>Hello World</li></ul></p>.

2 people like this

Share this post


Link to post
Share on other sites

I have tested Hanna with single {, ( and [, i.e. 

(hello)
[hello]
{hello} 
They all work fine in both PHP and Text mode.

Ryan, are these OK or they could throw up issues? Thx.

Share this post


Link to post
Share on other sites

I think it would be really cool if there was and easy (JSON?) way to import/export hanna codes (all or single). Maybe then we could setup a subforum to share them.

Otherwise this is amazing, thanks Ryan.

Share this post


Link to post
Share on other sites

I think it would be really cool if there was and easy (JSON?) way to import/export hanna codes (all or single). Maybe then we could setup a subforum to share them.

Otherwise this is amazing, thanks Ryan.

/site/assets/cache/HannaCode/ :). The PHP are stored as PHP files

Share this post


Link to post
Share on other sites

Is it just me or is Hanna version 1.0.4 broken? It no longer works - it outputs the raw tag :(

Don't know what's happening but even older versions do not work any more. I'm stumped. Ideas? Using it on 2.3 stable

Edited by kongondo

Share this post


Link to post
Share on other sites

/site/assets/cache/HannaCode/ :). The PHP are stored as PHP files

Haha, thats cool, I guess I could've taken a look before posting. Though a spot to officially discuss these maybe couldn't hurt. :P

Share this post


Link to post
Share on other sites

Is it just me or is Hanna version 1.0.4 broken? It no longer works - it outputs the raw tag  :(

Don't know what's happening but even older versions do not work any more. I'm stumped. Ideas? Using it on 2.3 stable

It's working for me at least, though I did change some things about the regex's in 0.0.4, so I might need to get more info about the context. What's an example of a tag that isn't working for you? What is the markup that surrounds it in your text? Also can you double check that "Hanna Code" is set as the textformatter for your body field (or whatever field you are using it in) in Setup > Fields > body > details?

Ryan, are these OK or they could throw up issues? Thx.

It should be fine to set your open/close tags to be whatever you want. Though [this] is a fairly common text construct, where as [[this]] is not. So if your [this] ever conflicts with the name of a Hanna Code, that could cause some confusion. As a result, I think it may be preferable to use open/close tags that don't duplicate things you would usually see in written copy. 

Share this post


Link to post
Share on other sites

I'm going to give this a go for inserting galleries on the fly. I think this combined with responsive CSS is pretty powerful stuff.

Share this post


Link to post
Share on other sites

It's working for me at least, though I did change some things about the regex's in 0.0.4, so I might need to get more info about the context. What's an example of a tag that isn't working for you? What is the markup that surrounds it in your text? Also can you double check that "Hanna Code" is set as the textformatter for your body field (or whatever field you are using it in) in Setup > Fields > body > details?

Sorry; I just wasted your precious time! I forgot to set it as my textformatter after I made a couple of changes!  :-[ Thanks :)

Share this post


Link to post
Share on other sites

What kills me about this module is that Ryan literally decided to make it because I had something similar in WordPress and needed a substitute solution in ProcessWire (as part of the move of CMS Critic to PW) otherwise I'd have a ton of weird shortcodes in my posts for no reason. He made this module, imported my code from the other module (called Hana Code in WP) and named his Hanna Code (after his daughter) and Poof! a module is born.

I am insanely jealous of his mad php skills (but glad they can be bought!)

10 people like this

Share this post


Link to post
Share on other sites

And we have you to thank for hiring him in the first place which led us to Hanna Code! Thank you!

4 people like this

Share this post


Link to post
Share on other sites

Ryan, brilliant stuff!
 

For me it won't work in my first attempt and it took me some time to figure out my failure.

You can't use the identifier "name" for a variable.

[[gallery name="Test"]]

I didn't found any comments on this issue, so perhaps it helps.

2 people like this

Share this post


Link to post
Share on other sites

Kent, that's correct–I'll update the readme file. The term "name" is set to the name of the Hanna code. This is provided to the PHP so that it can check the name of the code, just in case it needs it. Likewise, it's preferable not to use any API variable name for your attributes either. 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      First a note about my other modules...
      I have three existing modules that are similar in that they allow restrictions to be placed on repeating inputfields: Limit Repeater, Limit PageTable, Limit Table
      Restrict Repeater Matrix takes a different approach to the module configuration from those other modules. The module settings for Restrict Repeater Matrix are applied in the field settings rather in a module config screen. I think this new approach is better, but it means that it isn't practical to create different settings for different roles via the admin interface. Instead the module has a hookable method, allowing roles to be targeted and other advanced usages to be achieved via a hook. The result is that the module is more flexible.
      I intend to transition my other modules to the same approach over the coming weeks, but because this will result in breaking changes I will be releasing the updated modules under new names ("Restrict Repeater", etc) to avoid users upgrading via the Upgrades module without full awareness of the changes. The old modules will be marked as deprecated.
       
      Restrict Repeater Matrix
      A module for ProcessWire CMS/CMF. Allows restrictions and limits to be placed on Repeater Matrix fields.
      For any matrix type in a Repeater Matrix field you have the option to:
      Prevent drag-sorting of items Prevent cloning of items Prevent toggling of the published state of items Prevent trashing of items Limit the number of items that may be added to the inputfield Please note that restrictions and limits are applied with CSS/JS so should not be considered tamper-proof.
      Usage
      Install the Restrict Repeater Matrix module.
      For each matrix type created in the Repeater Matrix field settings, a "Restrictions" fieldset is added at the bottom of the matrix type settings:

      For newly added matrix types, the settings must be saved first in order for the Restrictions fieldset to appear. Set restrictions for each matrix type as needed. A limit of zero means that no items of that matrix type may be added to the inputfield.
      Setting restrictions via a hook
      Besides setting restrictions in the field settings, you can also apply or modify restrictions by hooking RestrictRepeaterMatrix::checkRestrictions. This allows for more focused restrictions, for example, applying restrictions depending on the template of the page being edited or depending on the role of the user.
      The checkRestrictions() method receives the following arguments:
      $field This Repeater Matrix field $inputfield This Repeater Matrix inputfield $matrix_types An array of matrix types for this field. Each key is the matrix type name and the value is the matrix type integer. $page The page that is open in ProcessPageEdit The method returns a multi-dimensional array of matrix types and restrictions for each of those types. An example of a returned array:

      Example hooks
      Prevent the matrix type "images_block" from being added to "my_matrix_field" in a page with the "basic-page" template:
      $wire->addHookAfter('RestrictRepeaterMatrix::checkRestrictions', function(HookEvent $event) { $field = $event->arguments('field'); $page = $event->arguments('page'); $type_restrictions = $event->return; if($field->name === 'my_matrix_field' && $page->template->name === 'basic-page') { $type_restrictions['images_block']['limit'] = 0; } $event->return = $type_restrictions; });  
      Prevent non-superusers from trashing any Repeater Matrix items in "my_matrix_field":
      $wire->addHookAfter('RestrictRepeaterMatrix::checkRestrictions', function(HookEvent $event) { $field = $event->arguments('field'); $type_restrictions = $event->return; if($field->name === 'my_matrix_field' && !$this->user->isSuperuser()) { foreach($type_restrictions as $key => $value) { $type_restrictions[$key]['notrash'] = true; } } $event->return = $type_restrictions; });  
      https://github.com/Toutouwai/RestrictRepeaterMatrix
    • By bernhard
      Hi,
      just stumbled over a little module that i built for my last project. it helped me to test performance of my rockdatatables module to generate 3000 random json datasets and i want to share it with you. maybe it saves some time for someone.
      https://gitlab.com/baumrock/RockDummyData/
      easy example:
      $rdd = $modules->get('RockDummyData'); for($i=0; $i<15; $i++) { // this has to be inside the for-loop to always get a new dummy $dummy = $rdd->getDummy(); echo date("d.m.Y H:i:s", $dummy->timestamp) . "<br>"; } more advanced:
      $json = new stdClass(); $json->data = array(); $rdd = $modules->get('RockDummyData'); for($i=0; $i<3000; $i++) { // this has to be inside the for-loop to always get a new dummy $dummy = $rdd->getDummy(); $obj = new stdClass(); $obj->name = $dummy->forename . ' ' . $dummy->surname; $obj->position = $dummy->job; $obj->office = $dummy->city; $obj->color = $dummy->color; $obj->start_date = new stdClass(); $obj->start_date->display = date('d.m.Y',$dummy->timestamp); $obj->start_date->sort = $dummy->timestamp; $obj->salary = rand(0,10000); $json->data[] = $obj; } echo json_encode($json); you have to store your random datasets on your own into the /data folder. there are several services for creating all kinds of random data on the web - if you know one service that allows sharing those datasets let me know and i can include common needed data into the module
    • By AndySh
      Hello!
      I need your assistance please. I purchased the module FormBuilder. Unfortunately, the module discontinued delivering customer submissions to e-mail box specified in the module settings. Direct mailing to the e-mail box works OK. The module settings stays the same and are correct, like "Send e-mail to administrator(s) is checked. The last version of FormBuilder 3.0 has been installed. Please advise how to resolve the issue becase I cannot get orders from customers anymore (((
    • By kixe
      As described in this post (https://processwire.com/talk/topic/8551-custom-urls-for-pages/?p=82742) the option 'Name Format Children' under the tab 'Family' in template settings doesn't work properly and also not as expected. I had a look inside the code and made some changes which are working properly, which offers much more options, more consistency and less code too.

      The result is the following. You have 3 Options for generating name and title, which could be combined in endless variations.
      Name is always derived from title, same like creating pages manually.
      type date: if function detects # character anywhere in the string, conversion will be: deletion of # and string will be used as format parameter for PHP date() function type field: if string is a fieldname of the parent page the value of this field will be used type string: if string doesn't fit to the 2 preceeding it will be taken as it is All parts (separated by comma) will be composed in the order of setting. You can use unlimited numbers of parts

      I made a pull request on github: https://github.com/ryancramerdesign/ProcessWire/pull/831

      Example screenshots

      Setting ...


      will result in


       
    • By kongondo
      FieldtypeRuntimeMarkup and InputfieldRuntimeMarkup
       
      Modules Directory: http://modules.processwire.com/modules/fieldtype-runtime-markup/
      GitHub: https://github.com/kongondo/FieldtypeRuntimeMarkup
       
      This module allows for custom markup to be dynamically (PHP) generated and output within a page's edit screen (in Admin).
       
      The value for the fieldtype is generated at runtime. No data is saved in the database. The accompanying InputfieldRuntimeMarkup is only used to render/display the markup in the page edit screen.
       
      The field's value is accessible from the ProcessWire API in the frontend like any other field, i.e. it has access to $page and $pages.
       
      The module was commissioned/sponsored by @Valan. Although there's certainly other ways to achieve what this module does, it offers a dynamic and flexible alternative to generating your own markup in a page's edit screen whilst also allowing access to that markup in the frontend. Thanks Valan!
       
      Warning/Consideration
      Although access to ProcessWire's Fields' admin pages is only available to Superusers, this Fieldtype will evaluate and run the custom PHP Code entered and saved in the field's settings (Details tab). Utmost care should therefore be taken in making sure your code does not perform any CRUD operations!! (unless of course that's intentional) The value for this fieldtype is generated at runtime and thus no data is stored in the database. This means that you cannot directly query a RuntimeMarkup field from $pages->find(). Usage and API
       
      Backend
      Enter your custom PHP snippet in the Details tab of your field (it is RECOMMENDED though that you use wireRenderFile() instead. See example below). Your code can be as simple or as complicated as you want as long as in the end you return a value that is not an array or an object or anything other than a string/integer.
       
      FieldtypeRuntimeMarkup has access to $page (the current page being edited/viewed) and $pages. 
       
      A very simple example.
      return 'Hello'; Simple example.
      return $page->title; Simple example with markup.
      return '<h2>' . $page->title . '</h2>'; Another simple example with markup.
      $out = '<h1>hello '; $out .= $page->title; $out .= '</h1>'; return $out; A more advanced example.
      $p = $pages->get('/about-us/')->child('sort=random'); return '<p>' . $p->title . '</p>'; An even more complex example.
      $str =''; if($page->name == 'about-us') { $p = $page->children->last(); $str = "<h2><a href='{$p->url}'>{$p->title}</a></h2>"; } else { $str = "<h2><a href='{$page->url}'>{$page->title}</a></h2>"; } return $str; Rather than type your code directly in the Details tab of the field, it is highly recommended that you placed all your code in an external file and call that file using the core wireRenderFile() method. Taking this approach means you will be able to edit your code in your favourite text editor. It also means you will be able to type more text without having to scroll. Editing the file is also easier than editing the field. To use this approach, simply do:
      return wireRenderFile('name-of-file');// file will be in /site/templates/ If using ProcessWire 3.x, you will need to use namespace as follows:
      return ProcessWire\wireRenderFile('name-of-file'); How to access the value of RuntimeMarkup in the frontend (our field is called 'runtime_markup')
       
      Access the field on the current page (just like any other field)
      echo $page->runtime_markup; Access the field on another page
      echo $pages->get('/about-us/')->runtime_markup; Screenshots
       
      Backend
       

       

       
      Frontend