Monday, 26 September 2016

Keyword arguments (kwargs) in Custom Views


Custom views are a great way to create widgets in TACTIC.   They combine HTML, CSS, server side Python and client Javascript all in a single self contained widget.  All views in TACTIC have a predefined variable named “kwargs” which contain parameters that are passed to the widget from some external source.  The kwargs variable is a simple dictionary of name / value pairs and represent keyword arguments for that widget.  These kwargs can be used to write highly functional general purpose widgets that can be reused.


In a TACTIC using the Custom Layout Editor, it can be assumed that there is always a kwargs variable which can be simply accessed in the Python section of the custom view.


color = kwargs.get(“color”) or “”
search_type = kwargs.get(“search_type”) or “”


These variables can be accessed in the HTML component using the following syntax:


<div class=”top_element” style=”color: ${color}”>
 <element view=”view1” search_type=”${search_type}”/>
</div>


Thus a variable take from the kwargs are passed from python to an HTML, first to set the color style and second, to pass the search_type to another view which will receive as a kwarg as well.


The variables defined in Python are also accessible in the styles section:


.top_element {
   color: ${color};
}


The kwargs variable is also passed along to the behavior section:


<behavior class=”top_element” event=”click”>
   alert( bvr.kwargs.search_key );
</behavior>


This makes the input variables through kwargs available to all parts of a TACTIC widget.  One often used technique is to go fill in the kwargs variable with custom key / value pairs to simplify the communication of data between Python and Javascript


server = TacticServerStub.get()
count = server.eval(“@COUNT(workflow/asset)”)
kwargs.count = count


And in Javascript


<behavior class=”top_element” event=”click”>
   alert(bvr.kwargs.count)
</behavior>


The kwargs value can be a complex data structure as well:


codes = server.eval(“@GET(workflow/asset.code”)
kwargs.codes = codes


And in Javascript


var codes = bvr.kwargs.codes;
for (var i = 0; i < codes.length; i++ ) {
   alert(codes[i]);
}


Put together, this provides a complete communication for transferring data for server side data to the client side, all encapsulated in a single widget.