Shiv The Third - Return of Tutorial
Continuing from my previous posts on Shiv, Shiv - A wrapper over Django and Shiv - Part Deux, I will now try to explain about various components involved in Shiv. In this post we will talk about Media and Element. In later parts, we will explore Tabs, Boxes, Widgets, Pages, and Caching.
Media classes define the various media used by all the containers of the Project. Shiv uses a naming convention for media classes. The media class of a container class named “ABC” should be “ABCMedia” and it must be derived from shiv.media.Media.
from shiv.media import Media class FeedbackBoxMedia(Media): template = 'master/BFeedback.html' css = ['master/BFeedback.css', 'common/ElementDefault.css'] js = ['master/BFeedback.js', 'common/FormsCommon.js', 'jquery.form.js'] images = {'title':'/static/images/prelogin/feedback-v3.png'}
The above Media class is for the container class FeedbackBox
Element is the lowest level container in Shiv. It gets instantiated by a Tab.
from shiv.callback import Callback from shiv.ajax import allowAnonymous from shiv.element import Element from shiv.json_utils import JsonResponse import json cb = Callback() class MyFirstElement(Element): def _prepare(self): self.context = { 'message': 'Hello', 'ajax_key': self.ajax_message.key } @staticmethod @allowAnonymous @cb.register def ajax_message(request): return JsonResponse(json.dumps({'message': 'Hello from Ajax'})
In the code above allowAnonymous ensures that Anonymous users can call this callback and cb.register registers this function as an Ajax Callback function and provides it a key. The ajax_message method can be called using a url with its key as one of the parameters. Look at the template and js below to understand how.
from shiv.media import Media class MyFirstElementMedia(Media): template = 'element.html' js = ['jquery.js', 'message.js']
<div class="myelem" data-id="{{ajax_key}}"> {{message}} </div>
$('.myelem').live('click', function(){ var data_id = $(this).attr("data-id"); $.get(AJAX_URL, { 'data_id': data_id }, function(response) { alert(response.message); }); });
..... <head> .... .... Other css declarations {% for c in css %} <link rel="stylesheet" type="text/css" href="{{c}}" /> {% endfor %} {% block page_css%} {%endblock %} .... .... </head> <body> ... ... </body> ... ... Other js declarations {% for j in js %} <script type="text/javascript" src="{{j}}"></script> {% endfor %} {% block page_js %} {% endblock %} <script type="text/javascript"> AJAX_URL = "{% url ajax_url %}" </script> </html>
... urlpatterns = patterns('', ..., ..., (r'^async/', include('shiv.urls')), ..., ...)
We will look into Tab next. And hopefully if I find enough time, we will discuss about Box and Widgets too.