Call php function in view from mustache and pass a mustache array value into the function call - kohana-3.3

I would like to pass an array value to a view function so that it can send back some HTML based on that value sent. I want my system to either send back textarea, textbox or radio button.
On my mustache I have {{#get_question}}{{type}}{{/get_question}} where type can have any value from ["input","radio","comment"] The main headache I have is how to call this function and pass the parameter.
I would like to have a php function get_question which extracts the value passed in {{type}}, if type is not text, I would like to pass the value of type to my partial call {{>}} and dynamically load the partial represented by the {{type}}
I got this code sample from Kohana forums:
Hello, {{#caps }}{{ text }}{{/ caps }}!
$m = new Mustache_Engine(array(
'helpers' => array(
'caps' => function() {return function($text, $m) {
return strtoupper($m->render($text));
}}
)
));
I can't seem to get it to work from my view since I have to enclose it in another function(){} block.
How do I go about this?

It's a headache because you're fighting against the fundamentals of Mustache :)
This is a bit backwards from the "Mustache way". Instead of trying to shoehorn in logic via lambdas, you should extract the logic into your view/viewmodel/model, and limit your template to simple sections and string interpolations. Something like this would do the trick:
{{# questions }}
{{# is_input }}{{> input }}{{/ is_input }}
{{# is_radio }}{{> radio }}{{/ is_radio }}
{{# is_comment }}{{> comment }}{{/ is_comment }}
{{/ questions }}
Then each question view/viewmodel/model would answer to is_input(), is_radio() and is_comment().

Related

How to insert '_' as htmlAttributes in razor?

This is probably a simple question, but to which I havent found an answer yet.
How to escape the ' _ ' when creating an HtmlElement in razor?
To render a '-' in the final Html we put an ' _ ', but to render an '_' (underscore), How do we escape it? I tryed '#:', but it didn't work, and didn't find any other options...
Example:
#Html.CheckBox("Access_Groups", false, new
{
#class = "input-control checkbox",
#data_group = "I', looking for data-group",
#Description_pt = "<----- I'm looking for Description_pt"
})
#data_group will render as data-group as expected, but...
#Description_pt will render as Description-pt, and that is not what is expected (don't know how to escape the _ for this)
thank you
If you look at the signature of Html.Checkbox, we can see that it takes an object for the htmlAttributes. Further, looking at the syntax, its actually a key based collection of objects. A Dictionary<string,object> fits that bill and allows you to absolutely specify the name of the html attributes that you want to add (note each key is typed exactly how we want it to display).
#Html.CheckBox("Access_Groups", false, new Dictionary<string,object>
{{"class", "input-control checkbox"},
{"data-group", "I', looking for data-group"},
{"Description_pt", "SomeValue"}})
This renders the following HTML
<input Description_pt="SomeValue" class="input-control checkbox"
data-group="I', looking for data-group" id="Access_Groups"
name="Access_Groups" type="checkbox" value="true" />
Have you tried the HTML character code for underscore, i.e., _?

Spaces being turned into in angular

I'm using ng_repeat to display text from an object. On the rails backend I call strip_tags(text) to remove html. When looking at the output it looks fine. Even when looking at the object in 'view source' it looks fine.
It only looks weird when you look at the text that is actually rendered from the ng_repeat - after a certain point (200 words in the example below) every space is replaced by an
This is causing the text to overflow the div. Any suggestions for dealing with this?
Edit: Some of the code (simplified)
JS:
$scope.init = function(id){
$scope.episodes = gon.episodes
Haml:
.episode-edit{ng_repeat:"episode in episodes"}
%p {{episode.sanitized_summary}}
You should try ng-bind-html. Your snippet would look like
<p ng-bind-html="YourObject"></p>
You can use it in ng-repeat as well.
If you want to secure the data first then include $sce service in your controller. Your snippet would be like
var ExampleCtrl = function($scope, $sce) {
$scope.YourObject = $sce.trustAsHtml($scope.YourObject); // that's it
}
Sorry, turns out it had nothing to do with angular, more to do with Ruby.
Ruby's whitespace regex doesn't capture unicode non-breaking space.
Instead of str.gsub(/\s/m, ' ') you have to use str.gsub(/[[:space:]]/m, ' ')

How to pass html parameter in Google Closure Template

Guys I want to pass a parameter that contains html characters in Google Closure Template, but all I get is literal html texts. How to do this?
What I have tried so far is this :
{template .modal autoescape="strict" kind="html"}
{$html_content}
{/template}
I have been reading this but it's not very helpful. Thanks
{template .modal}
{$html_content |noAutoescape}
{/template}
Is going to print your HTML. But consider that using |noAutoescape in your templates is discouraged.
Discouraged: It's easy to accidentally introduce XSS attacks when the assertion
that content is safe is far away from where it is created. Instead,
wrap content as sanitized content where it is created and easy to
demonstrate safety.– Google Closure Templates Functions and Print Directives
Or if you are sure $html_content is "safe" HTML, you can ordain it right where you pass parameters to the template:
goog.require('soydata.VERY_UNSAFE');
goog.require('template.namespace');
var container = document.getElementById('modal');
var html = '<strong>HTML you trust!</strong>';
container.innerHTML = template.namespace.modal({
html_content: soydata.VERY_UNSAFE.ordainSanitizedHtml(html);
});
Then your initial template is going to print HTML as it is:
/**
* #param html_content HTML markup
*/
{template .modal autoescape="strict" kind="html"}
{$html_content}
{/template}

Escape Html Text in ZF2

I have a text like this:
<p><strong>Lorem</strong> ipsur </p>
To see a text without html tags in Zend Framework 2 how can I do?
I tried to put:
<?php echo $this->escapehtml($array['text']); ?>
I read that for security is not good to do:
<?php echo $array['descrizione']; ?>
Im not sure if i understand the question, since i dont know the contents of your arrays.
basicaly if you want to scape the contents of a variable, let's say, $input, you have to call, as you mentioned
$this>escapeHtml($input)
Actually, the PhpRenderer includes a selection of helpers you can use for this purpose: EscapeHtml, EscapeHtmlAttr, EscapeJs, EscapeCss, and EscapeUrl.
You can read about this here
Also, if you want more control, you can use Zend\Escaper, that in 2 lines of code allow you to escape html, like this
$escaper = new Zend\Escaper\Escaper('utf-8');
$output = $escaper->escapeHtml($input);
or escape attributes, like this
$escaper = new Zend\Escaper\Escaper('utf-8');
$output = $escaper->escapeHtmlAttr($input);
I recommend you read the 3 links, they are very short and would give you a better undestanding of what you are doing.
At this moment there is no option in escapeHtml to allow certain tags. What you have to do in these specific cases is to modify the returned value:
<?php
$str = $this->escapehtml($array['text']); ?>
$str = preg_replace(
array('#href="(.*)"#', '#<(/?(?:pre|a|b|br|em|u|ul|li|ol|p|strong)(\shref=".*")?/?)>#' ),
array( 'href="\1"', '<\1>' ),
$str
);
echo $str;
You can add/remove tags from the part pre|a|b|br|em|u|ul|li|ol|p|strong to your needs. Also this code will allow anchor tags with href only.

Kendo UI Grid in MVC with Conditional Custom Command Button

I have a KendoUI Grid I'm using an MVC web application, all working fine however I want to add a custom command button that is shown conditionally in the UI and simply executes a command on my controller passing it the required parameter.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click())
The command is specified as above but I only want the button to show when the DataItems IsLocked property is true.
I also cannot figure out how to just call and method on the controller rather. I cannot find a demo of this on the Kendo site and not sure how to move this forward.
Here is a specific example for using client templates for conditional command buttons.
const string ShowUpdateButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-edit' href='\\#'><span class='k-icon k-edit'></span>Update</a>#}#";
const string ShowReverseButton = "#if (IsNetReversal == false) {#<a class='k-button k-button-icontext k-grid-reverse' href='/JournalDetail/Reverse/#: ID #' ><span class='k-icon k-reverse'></span>Reverse</a>#}#";
const string ShowDeleteButton = "#if (IsAdjustment == true) {#<a class='k-button k-button-icontext k-grid-delete' href='\\#'><span class='k-icon k-delete'></span>Delete</a>#}#";
You can do the template inline but I find it easier (particularly for multiple buttons) if you declare constants and then use string.format to concatenate them.
col.Template(o => o).ClientTemplate(string.Format("{0}{1}{2}", ShowUpdateButton, ShowDeleteButton, ShowReverseButton));
The upside is it will work with popup editor whereas jquery hacks will ignore the conditional status when a user cancels out of edit. A cancel from the popup editor will restore the grid row from the viewmodel or wherever Kendo stores it which results in button states from before any jquery/javascript hack. The method above will also auto-wire the standard commands since I copied their HTML output for the client template.
The downside is that if Kendo changes their pattern for command buttons the client template may fail. I tired several other methods besides this one and the downside to this method seems better than the other methods.
Note on Kendo Forums: As of the date of this post, they do not appear to allow people who do not pay for support to post to the forums so I would suggest posting questions here instead. They monitor Stack Overflow and in my experience they seem to answer questions more quickly here.
Use template column instead - via the ClientTemplate method.
Conditional templates are covered here and multiple times on the forums - the Command columns is not that flexible.
As of the December 2018 release of Kendo, you can now conditionally display custom buttons more easily, but it still relies on JavaScript to do its work, this function should be defined before your dataGrid or you'll run into issues.
function showCommand(dataItem) {
console.log("determining to hide or show" + dataItem);
// show the Edit button for the item with Status='New'
if (dataItem.Status == 'New') {
return true;
}
else {
return false;
}
}
Then the code for the Grid.
.Columns (columns => {
columns.Command (
command => command.Custom ("Approve")
.Visible ("showCommand")
.Click ("approveFunc")
)
.Width (100)
.HeaderTemplate ("Actions")
})
You can control custom command button visibility by Visible property.
columns.Command(command => command.Custom("UnlockAccount").SendDataKeys(true).Click().Visible("unlockAccountVisible"))
Visible property accepts JS function name and passes current dataItem as an argument.
JS function that evaluates button visibility:
<script>
function unlockAccountVisible(dataItem) {
// show the UnlockAccount button only when data item property IsLocked == true
return dataItem.IsLocked;
}
</script>
Read more in Show Command Buttons Conditionally kendo-ui documentation article.

Resources