How to pass PHP data to block's view.js?
Permalink
Hello World!
I'm trying to figure out the best way to pass some PHP data to a block's view.js code. Specifically: I create a PageList and store the pages in an array. Inside view.js I want to build up a list of objects, that are based on the page data generated by C5, plus associate a DOM object for each page. I don't know how to start. I figured that I could print the data as an array of JSON objects in view.php, but I would not like to mix the presentation part with this kind of logic. Anyone got a better idea?
I'm trying to figure out the best way to pass some PHP data to a block's view.js code. Specifically: I create a PageList and store the pages in an array. Inside view.js I want to build up a list of objects, that are based on the page data generated by C5, plus associate a DOM object for each page. I don't know how to start. I figured that I could print the data as an array of JSON objects in view.php, but I would not like to mix the presentation part with this kind of logic. Anyone got a better idea?
You could add some json in a script section using the (EDIT - corrected the method/event handler to use) on_page_view() method of the block controller and adHeaderItem or addFooterItem.
The json would need to be a global variable or attached as a data attribute to a relevant dom element. But by using this method in the controller, it would stay completely outside of your view code.
Having said that, In most cases I would probably just echo it in the view or do an ajax callback as Remo suggested.
The json would need to be a global variable or attached as a data attribute to a relevant dom element. But by using this method in the controller, it would stay completely outside of your view code.
Having said that, In most cases I would probably just echo it in the view or do an ajax callback as Remo suggested.
Hey guys! Thanks for you suggestioins! I was wondering: if I would write a tools script, how would it (could it?) communicate with C5? I would need to use and manipulate page lists and custom page attributes. So how would I connect my script to C5? Can I?
The advantage of tools scripts is that they run within a minimal c5 environment , so you can load any of the API with Loader::etc, just as you would from your block controller.
For an example of tools in use, have a look at my AJAX Lessons howto & addon. Its getting a bit dated, but all the basic info and techniques are still valid.
Thank you for your help guys!
The combination of these technologies (JS + PHP) sometimes leads to code that doesn't look perfectly elegant.