Why use templates in Kohana? - templates

I don't understand the purpose of using templates in Kohana. I see almost no difference in the process of building a view with a template controller vs a regular controller, except that the template controller is tied to a given template and so is less flexible. What are the advantages?
Building view with regular controller:
Class Controller_Hello extends Controller
{
public function action_index()
{
$view = View::factory('page');
$view->page_title = 'My Hello App';
$view->content = 'hello, world!';
$view->sidebar = View::factory('parts/sidebar');
$this->response->body($view);
}
}
Building view with template controller:
Class Controller_Hello extends Controller_Template
{
public $template = 'page';
public function action_index()
{
$this->template->page_title = 'My Hello App';
$this->template->content = 'hello, world!';
$this->template->sidebar = View::factory('parts/sidebar');
}
}

Controller_Template is just an example of how you can implement your own templating-system.
It is not ready-to-use solution (at least for my projects usually). Check this one controller (it is also not ready-to-use solution but possibly it will help you understand point of extending different controllers for different purposes): http://pastie.org/2563595

I am sure there are other, maybe better solutions for templating systems. But why am I using templates in Kohana?
Think about multiple pages, all based upon one layout/design scheme. So I build a template controller using a certain view, defining layout/design, defining content, header and footer "areas". In the template controller I am loading the CSS files and script files, setting the title and meta values of the website, because every single site is using these CSS/script files with the same meta values and title.
So in every Controller extending the template controller I don't need to load the CSS/script files anew, set the meta values and title etc... But I could change all these values, maybe add a CSS file only for a single site.
Maybe all the mentioned sites have the same footer and/or header: I assign the header/footer view to the template within the template controller, so I don't need to do that in all the controller extending the template controller. Or all actions in one controller have the same header/footer, so I assignt he header and footer few in the before() function of the controller...
For me templates in kohana are a good utility for building small web applications.

Related

How to set Joomla template for user/visit

I want to use specific Joomla template (with no navigation, no top and bottom) for users that connect to website through my mobile app with iframe in it. I assume that this users will start connection from specific address with tmpl param (or something similar) but is there a way to lock this template for these users?
Maybe there is some plugin to set template in session data and override default template choice?
There is a Joomla extension called Template Assigner - http://extensions.joomla.org/extension/template-assigner . It does exactly what you want.
Plugin allows me to set template only for specyfic user group, not to switch template accordingly to url but thanks to Your idea I created very simple plugin to do this, code below:
defined('_JEXEC') or die;
class plgSystemMobiler extends JPlugin
{
public function onAfterInitialise()
{
$app = JFactory::getApplication();
$jinput = $app->input;
if (isset($_REQUEST['mobile'])) $par=(int)$_REQUEST['mobile'];
if (isset($par)) $jinput->cookie->set('mobile', $par, time() + 100000, $app->get('cookie_path', '/'), $app->get('cookie_domain'), $app->isSSLConnection());
$cookie=$jinput->cookie->get('mobile');
if (intval($cookie)>0) JFactory::getApplication()->input->set('templateStyle', intval($cookie));
}
}

How can I dynamically render HTML using Meteor Spacebars templates?

So let's say I'm storing <div>{{name}}</div> and <div>{{age}}</div> in my database.
Then I want to take the first HTML string and render it in a template - {{> template1}} which just renders the first string with the {{name}} handlebar in it. Then I want to give that newly generated template/html data, so that it can fill in the handlebar with the actual name from the database, so that we would get <div>John</div>. I've tried doing
<template name="firstTemplate">
{{#with dataGetter}}
{{> template1}}
{{/with}}
</template>
Where template1 is defined as
<template name="template1">
{{{templateInfo}}}
</template>
And templateInfo is the helper that returns the aforementioned html string with the handlebar in it from the database.
dataGetter is just this (just an example, I'm working with differently named collections)
Template.firstTemplate.dataGetter = function() {
return Users.findOne({_id: Session.get("userID")});
}
I can't get the {{name}} to populate. I've tried it a couple of different ways, but it seems like Meteor doesn't understand that the handlebars in the string need to be evaluated with the data. I'm on 0.7.0 so no Blaze, I can't upgrade at the moment due to the other packages I'm using, they just don't have 0.8+ version support as of yet. Any ideas on how I can get this to work are much appreciated.
In 1.0 none of the methods described above work. I got this to work with the function below defined in the client code. The key was to pass the options { isTemplate: true} to the compile function.
var compileTemplate = function(name, html_text) {
try {
var compiled = SpacebarsCompiler.compile(html_text, { isTemplate:true });
var renderer = eval(compiled);
console.log('redered:',renderer);
//Template[name] = new Template(name,renderer);
UI.Template.__define__(name, renderer);
} catch (err){
console.log('Error compiling template:' + html_text);
console.log(err.message);
}
};
The you can call with something like this on the client:
compileTemplate('faceplate', '<span>Hello!!!!!!{{_id}}</span>');
This will render with a UI dynamic in your html
{{> Template.dynamic template='faceplate'}}
You can actually compile strings to templates yourself using the spacebars compiler.. You just have to use meteor add spacebars-compiler to add it to your project.
In projects using 0.8.x
var compiled = Spacebars.compile("<div>{{name}}</div> and <div>{{age}}</div>");
var rendered = eval(compiled);
Template["dynamicTemplate"] = UI.Component.extend({
kind: "dynamicTemplate",
render: rendered
});
In projects using 0.9.x
var compiled = SpacebarsCompiler.compile("<div>{{name}}</div> and <div>{{age}}</div>");
var renderer = eval(compiled);
Template["dynamicTemplate"] = Template.__create__("Template.dynamicTemplate", rendered);
Following #user3354036's answer :
var compileTemplate = function(name, html_text) {
try {
var compiled = SpacebarsCompiler.compile(html_text, { isTemplate:true }),
renderer = eval(compiled);
console.log('redered:',renderer);
//Template[name] = new Template(name,renderer);
UI.Template.__define__(name, renderer);
} catch (err) {
console.log('Error compiling template:' + html_text);
console.log(err.message);
}
};
1) Add this in your HTML
{{> Template.dynamic template=template}}
2) Call the compileTemplate method.
compileTemplate('faceplate', '<span>Hello!!!!!!{{_id}}</span>');
Session.set('templateName','faceplate');
Save the template name in a Session variable. The importance of this is explained in the next point.
3) Write a helper function to return the template name. I have used Session variable to do so. This is important if you are adding the dynamic content on a click event or if the parent template has already been rendered. Otherwise you will never see the dynamic template getting rendered.
'template' : function() {
return Session.get('templateName');
}
4) Write this is the rendered method of the parent template. This is to reset the Session variable.
Session.set('templateName','');
This worked for me. Hope it helps someone.
If you need to dynamically compile complex templates, I would suggest Kelly's answer.
Otherwise, you have two options:
Create every template variation, then dynamically choose the right template:
eg, create your templates
<template name="displayName">{{name}}</template>
<template name="displayAge">{{age}}</template>
And then include them dynamically with
{{> Template.dynamic template=templateName}}
Where templateName is a helper that returns "age" or "name"
If your templates are simple, just perform the substitution yourself. You can use Spacebars.SafeString to return HTML.
function simpleTemplate(template, values){
return template.replace(/{{\w+}}/g, function(sub) {
var p = sub.substr(2,sub.length-4);
if(values[p] != null) { return _.escape(values[p]); }
else { return ""; }
})
}
Template.template1.helpers({
templateInfo: function(){
// In this context this/self refers to the "user" data
var templateText = getTemplateString();
return Spacebars.SafeString(
simpleTemplate(templateText, this)
);
}
Luckily, the solution to this entire problem and any other problems like it has been provided to the Meteor API in the form of the Blaze package, which is the core Meteor package that makes reactive templates possible. If you take a look at the linked documentation, the Blaze package provides a long list of functions that allow for a wide range of solutions for programmatically creating, rendering, and removing both reactive and non-reactive content.
In order to solve the above described problem, you would need to do the following things:
First, anticipate the different HTML chunks that would need to be dynamically rendered for the application. In this case, these chunks would be <div>{{name}}</div> and <div>{{age}}</div>, but they could really be anything that is valid HTML (although it is not yet part of the public API, in the future developers will have more options for defining this content in a more dynamic way, as mentioned here in the documentation). You would put these into small template definitions like so:
<template name="nameDiv">
<div>{{name}}</div>
</template>
and
<template name="ageDiv">
<div>{{age}}</div>
</template>
Second, the definition for the firstTemplate template would need to be altered to contain an HTML node that can be referenced programmatically, like so:
<template name="firstTemplate">
<div></div>
</template>
You would then need to have logic defined for your firstTemplate template that takes advantage of some of the functions provided by the Blaze package, namely Blaze.With, Blaze.render, and Blaze.remove (although you could alter the following logic and take advantage of the Blaze.renderWithData function instead; it is all based on your personal preference for how you want to define your logic - I only provide one possible solution below for the sake of explanation).
Template.firstTemplate.onRendered(function() {
var dataContext = Template.currentData();
var unrenderedView = Blaze.With(dataContext, function() {
// Define some logic to determine if name/age template should be rendered
// Return either Template.nameDiv or Template.ageDiv
});
var currentTemplate = Template.instance();
var renderedView = Blaze.render(unrenderedView, currentTemplate.firstNode);
currentTemplate.renderedView = renderedView;
});
Template.firstTemplate.onDestroyed(function() {
var renderedView = Template.instance().renderedView;
Blaze.remove(renderedView);
});
So what we are doing here in the onRendered function for your firstTemplate template is dynamically determining which of the pieces of data that we want to render onto the page (either name or age in your case) and using the Blaze.With() function to create an unrendered view of that template using the data context of the firstTemplate template. Then, we select the firstTemplate template element node that we want the dynamically generated content to be contained in and pass both objects into the Meteor.render() function, which renders the unrendered view onto the page with the specified element node as the parent node of the rendered content.
If you read the details for the Blaze.render() function, you will see that this rendered content will remain reactive until the rendered view is removed using the Blaze.remove() function, or the specified parent node is removed from the DOM. In my example above, I am taking the reference to the rendered view that I received from the call to Blaze.render() and saving it directly on the template object. I do this so that when the template itself is destroyed, I can manually remove the rendered view in the onDestroyed() callback function and be assured that it is truly destroyed.
A very simple way is to include in the onRendered event a call to the global Blaze object.
Blaze.renderWithData(Template[template_name], data ,document.getElementById(template_id))

How to override Ember.View such that all templates are searched for under a namespace

I'm using ember-rails to take care of handlebars compilation and the rails app will have multiple Ember applications (depending on which page the user is on). To better handle file management I'd like to organize the templates under a different folder per app. However, I don't want to have to create a separate view for each template just to specify the templateName. Is there a good way to Override Ember.View for each application such that it will always look for templates under a particular namespace?
You can override the template resolver to accomplish this. The basic idea is to make sure that the build system like ember-rails compiles templates in the form,
Ember.TEMPLATES['namespace/foo/bar'] = ...
Then you can override the template resolver to prefix that namespace onto the template name.
App = Ember.Application.create({
templateNamespace: 'initech',
resolver: Ember.DefaultResolver.extend({
resolveTemplate: function(parsedName) {
parsedName.fullNameWithoutType = App.templateNamespace + '/' + parsedName.fullNameWithoutType;
parsedName.name = App.templateNamespace + '/' + parsedName.name;
return this._super(parsedName);
}
})
});
Here's a jsbin example. The templates are embedded in the example but would come from the initech directory in your case.

GRAILS: Can I call service logic from _FORM.GSP template?

I'm refactoring scaffolding templates and I hit a wall with this issue:
I was trying to call service (some security logic) from template _FORM.GSP - but in the code part, not in the output part
I've read and tried what was suggested in here: How do I call a Grails service from a gsp?
I've tried to use taglib, but my knowledge of grails may not be extensive enough for that
I've tried add import and def to the beginning of _FORM.GSP file (both grailsApplication and application instantiation of service were crashing on missing property application resp. missing property grailsApplication)
I've even tried to call the taglib from the code both directly as method isAllowedToEdit and also as g.isAllowedToEdit both crashing on unknown method resp. "no such property g"
it seems that template _form.gsp has different rules than standard gsp view
I want to do something like this:
private renderFieldForProperty(p, owningClass, prefix = "") {
boolean hasHibernate = pluginManager?.hasGrailsPlugin('hibernate')
boolean display = true
boolean required = false
if (hasHibernate) {
cp = owningClass.constrainedProperties[p.name]
display = (cp ? cp.display : true)
required = (cp ? !(cp.propertyType in [boolean, Boolean]) && !cp.nullable && (cp.propertyType != String || !cp.blank) : false)
}
/* trying to do this part */
// I want to assign value to cp.editable - so later I can render read-only fields in renderEdit
if (!mySecurityService.canEdit(springSecurityService.currentUser, owningClass.getClass(), actionName, p.name)) {
cp.editable = false
}
/* trying to do this part */
if (display) { %>
<div class="fieldcontain \${hasErrors(bean: ${propertyName}, field: '${prefix}${p.name}', 'error')} ${required ? 'required' : ''}">
<label for="${prefix}${p.name}">
<g:message code="${domainClass.propertyName}.${prefix}${p.name}.label" default="${p.naturalName}" />
<% if (required) { %><span class="required-indicator">*</span><% } %>
</label>
${renderEditor(p)}
</div>
<% } } %>
if there is any way to assign cp.editable - I'll try your suggestions
it seems that template _form.gsp has different rules than standard gsp view
The generated _form.gsp works same as other gsps but the template inside the scr/templates/scaffolding/ is different. Customizing the templates like you are doing is a bit more tricky. Keep in mind that the logic you are writing is for Grails on how to generate views(gsp). Meaning you are telling Grails to check some logic before generating the views in memory or in the file. You might be able to accomplish that to some extend for dynamic (in memory) scaffolding at run-time but for sure not for static scaffolding. That's because Grails
is not aware of currentUser when generating the templates.
Your problem will be much simpler if you generate your views and then customize them instead of modifying their templates. Then you can inject your services and do other checks. However, as you also mentioned those logics are better off in a tag library here.
Also since you mentioned security, rendering a field non-editable does not guaranty inability to edit your fields. I would suggest to put the check logic inside your controller for example in SAVE or UPDATE action to prevent any unauthorized user editing fields.
Did you try this?
<%# page import="com.myproject.MyService" %>
<%
def myService = grailsApplication.classLoader.loadClass('com.myproject.MyService').newInstance()
%>
this will work for sure.
go through this link : click here

Symfony2: global variables in php templating engine

There is a cookbook for adding globals to the twig templating engine, but it doesn't get into doing the same thing for the php engine. How would I do this?
So I might have something like:
# config.yml
someSortOfReferenceToThePHPEngineInstance:
calls:
- [ addGlobals, ["foo", "bar"] ]
- [ addGlobals, ["myService", "#myService"] ]
And then access those like:
// templateName.contentType.php
<?
echo $foo; // echos "bar"
echo $myService->myMethod($foo); // echos the result of modifying "bar" with "myMethod" method of "myService" service
I could not find any documention on this for the PHP engine...
What does work however is:
Config:
//config.yml
parameters:
hello: "YO!"
PHP Template:
// index.html.php
<?php
print $view->container->parameters['hello'];
This does not fit as nicely as the twig convention... Maybe there is better way - I have not debugged any further...
Here are a couple of options:
If you create a base controller that all others inherit from, you can override symfony's render function and add keys to the parameters argument, like:
public function render($view, array $parameters = array(), Response $response = null){
if(!array_key_exists("bar", $parameters){
$parameters["foo"] = $this->get("foo");
}
if(!array_key_exists("bar", $parameters){
$parameters["bar"] = $this->get("bar");
}
return parent::render($view, $parameters, $response);
}
This is the only way I see to modify the "global" variables "globally", though they'll not be available in any views rendered by controllers you don't create (of course, those'll likely be done in Twig anyway and you can use the normal twig means of adding functionality).
The PHP rendering engine has what're called "helpers", which you can access via array keys of $view, like:
$view["foo"]->doSomething();
We created a class for easily making services into helpers:
use Symfony\Component\Templating\Helper\Helper as BaseHelper;
class Helper extends BaseHelper{
protected $name;
public $service;
public function __construct($name, $service){
$this->name = $name;
$this->service = $service;
}
public function __get($name){
if(isset($this->service->$name)){
return $this->service->$name;
}
}
public function __call($name, $arguments){
if(method_exists($this->service, $name)){
return call_user_func_array(array($this->service,$name), $arguments);
}
}
public function getName(){
return $this->name;
}
}
Then in our configuration under the services we'd add:
helper.foo:
class: %helper.class%
arguments:
name: "foo"
helper: "#foo"
tags:
- { name: templating.helper, alias: foo }
This would theoretically be available then to any view files, even those with controllers you don't have control of.
I had a very same problem. For some reason this feature is only available for Twig templating with TwigBundle. Both Twig and PHP templating engines provide possibility to define global variables, but only Twig engine has configuration for that. For me the only real way to achieve that is something you proposed in the question post - to define method calls (and this is the way Twig globals are registered).
Problem is, that with DI extensions you can't access service definition from outside your extension, so you can't add these calls from your DI extension. The way for me was to do that with DI compiler pass.
But I'm also developer of ChillDevViewHelpersBundle and since I was facing this problem in most of my projects I decided to implement it there for common use and you can use 0.1.8 release for this feature.