Question
I want to know if there is an alternative syntax to output data in Vue.js, instead of the curly braces, like the ng-bind Angular directive.
Reading the docs, it seems that Vue.js accepts only tag properties with the v-bind directive, but I want it to work with the inner html too.
Context
I want to output data using PHP and, once the page is loaded, manage it with Vue. Imagine the next situation:
We want this output:
<div>Hello</div>
First, we output the data with php
<div><?php echo $hello_string ?></div>
After that, we want to be able to change the content with Vue. The current syntax is;
<div>{{ hello_string }}</div>
We can't mix the two syntaxes, so I need something like this:
<!--Ideal syntax for mixing vue and php-->
<div v-bind:innerhtml="hello_string"><?php echo $hello_string ?></div>
Thank you for your help.
You could use the v-text directive:
<div v-text="hello_string"></div>
<!-- same as -->
<div>{{ hello_string }}</div>
or the v-html:
<div v-html="html"></div>
<!-- same as -->
<div>{{{ html }}}</div>
Vue.component({
el:'#app',
data:function(){
return {
hello_string:"<?php echo json_encode($hello_string) ?>"
};
}
});
Then in HTML:
<div id="app><div>{{ hello_string }}</div></div>
Basically you need to use PHP to fill your javascript variables, whether you do it through AJAX or just printing out the variables like above is up to you. You probably need to encode it to JSON or at least make sure quotes are escaped. On the front end, let Vuejs manage the view rather than printing directly into it with PHP.
Related
i have an ng-repeat but i need to use Angular expression inside javascript of my html page(of course app and controller are declared, but have not been posted here):
<div ng-repeat="eleRubrique in scopeComplet">
<script type="text/javascript">
alert('index ' + {{$index}});
</script>
</div>
That does not work. what would be a workaround ?
Thank you for an answer.
I think this would work for you
<div ng-repeat="eleRubrique in scopeComplet" ng-init="alert('index ' + $index)"></div>
And if you would need a more complex script I would recommend to write a function for that and call the function from ng-init
You should not use double curly braces {{}} in JavaScript. They are meant for HTML only in Angular.
Since the JavaScript code in your HTML has nothing to do with the view, can you not achieve the same goal in the controller?
I know there are already a few questions like mine but I wasn't able to fix my problem with their solutions.
I got this code in an external html file to include it in others files:
<div class="header">
<h1 class="replace-me">I'am a placeholder</h1>
</div>
The "file" above gets included into this "file":
<h2 style="display: none" class="variable">Hey, I'm a variable</h2>
The Variable from the second code should replace the content of the h1 tag in the first code. I know this isn't a forum to get free codes, I just want some inspirations or suggestions. Thanks Guys!
You can replace the html of one element with the html of another element, like so:
$(".replace-me").html($(".variable").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
<h1 class="replace-me">I'am a placeholder</h1>
</div>
<h2 style="display: none" class="variable">Hey, I'm a variable</h2>
However, as Rama Schneider pointed out, you might want to get your content in a different way than html.
Also note that this jQuery-solution is done client-side. If you already know the content when serving the initial HTML, you want to do this server-side.
If you have control over the external file, I'd suggest rewriting things so the external file serves a json object of some sort and work with your data from there.
Otherwise it's a simple matter of using JQuery to get the html contents from the variable and use that value to replace the html contents of the 'replace-me'.
You should solve this on server-side if you can. Make the common template a function, like this:
function getHeader($content) { ?>
<div class="header">
<h1 class="replace-me"><?php echo $content; ?></h1>
</div> <?php
}
calculate $content before you call the function and pass it to the function. If you cannot make this a function and you get this as it is from a third-party source, then you can do it via Javascript, like this:
<script type="text/javascript">
document.getElementsByClassName("header")[0].getElementsByClassName("replace-me")[0].innerHTML = "<?php echo $content; ?>";
</script>
Make sure you add this script after the header tag was loaded.
I have a problem using ng-style with ng-repeat.
This is my code:
<div style="display:table-row" ng-repeat="row in Data.Communications" id="{{row.Guid}}">
<div style="display:table-cell;">
<img ng-src="{{row.Path}}" ng-show="row.Path" ng-style="row.Style" />
<i class="{{row.Icon}}" ng-show="row.Icon" ng-style="row.Style"></i>
</div>
</div>
This is the JSON (Loaded server-side from a DB):
$scope.Data: {"LastUpdate":"23/03/2016 11:45","Communications":[{"Guid":"2","Path":null,"Icon":"fa fa-warning","Style":"{'color':'#ffff00'}"},{"Guid":"1","Path":null,"Icon":"fa fa-warning","Style":"{'color':'#ffff00'}"},{"Guid":"3","Path":"/images/blink_yellow.gif","Icon":null,"Style":"{'width':'15px', 'height':'15px'}"}]}
The "Style" is not applied to my elements. Could someone help me to solve this problem?
Basically you have strigified JSON, do parse it before assign it to ng-style
ng-style="doParseToJson(row.Style)"
Code
$scope.doParseToJson = function(style){
return JSON.parse(style);
}
Also make sure response should be wrap with " double qoutes instead of single quotes like '{"color":"#ffff00"}' to keep it valid for parsing the JSON.
I have a php function as shown below, which takes in an array that has values from an SQL query (in another, not shown function). In this case, the SQL query returns a set of filenames and their associated picture names.
// Take in an array of filters;
// each element is a dictionary of column name
// to the value of that row from SQL query
function displayFilters($filters) {
foreach($filters as $filter){
//output images in img tags, with their appropriate classes
echo " <div class='w3-quarter'>
<div class='w3-card-2'>
<img src='images/".$filter['File_Name']."' style='width:100%'>
<div class='w3-container'>
<h4>".$filter['Filter_Name']."</h4>
</div>
</div>
</div>";
}
}
Now, this works fine and will properly display the images as I want. However, I keep having to modify this code, change classes, properties and what not, and if I need to add/modify to the div, I have to go into this function to change everything. Is there a better way to do this than going into the echo function to change it? I'd rather not have to use Javascript if possible, but if that is the only clean way to do it, can someone point me to a way to do this?
<?php function displayFilters($filters) {
foreach($filters as $filter){ ?>
//output images in img tags, with their appropriate classes
<div class='w3-quarter'>
<div class='w3-card-2'>
<img src='images/<?=$filter['File_Name']>' style='width:100%'>
<div class='w3-container'>
<h4><?=$filter['Filter_Name']></h4>
</div>
</div>
</div>
<?php
}
} ?>
I do it this way and it seems easy than learning a new template engine
Use a PHP Template Engine
http://www.smarty.net/
Smarty is fast and lean with a small memory footprint.
http://twig.sensiolabs.org/ (Looks remarkably like Dwoo)
Twig is a modern template engine for PHP (Fast, Secure, Flexible)
http://dwoo.org/ (Inspired by Smarty)
Dwoo is a templating system used to make creating websites easier and more structured.
http://platesphp.com/ (Inspired by Twig)
Plates is a native PHP template system that’s fast, easy to use and easy to extend.
http://phptal.org/
PHPTAL is a PHP implementation of ZPT work. To be short, PHPTAL is a XML/XHTML template library for PHP.
I have written how to retrieve query and how to display in below code.
You can use this one. you can also use image tag within table <tr> tag.
$con=mysqli_connect('localhost','username','password','databasename');
$sql="SELECT `COL 1` , `COL 2` , `COL 3` , `COL 4` , `COL 5` , `COL 12` FROM `TABLE` WHERE 1 ORDER BY `COL 3` ;";
$result=mysqli_query($con,$sql);
<table style="width:100%" >
<tr>
<th>Col1</th>
<th>Clo2</th>
<th>Col3</th>
</tr>
<?
while ($row=mysqli_fetch_row($result))
{
echo "<tr><td>".$row[0]."</td><td>".$row[1]."\t".$row[2]."\t".$row[3]."\t".$row[4]."</td><td>".$row[5]."</td></tr>";
}
?>
</table>
I just started using Mustache and I like it so far, but this has me perplexed.
I am using the GitHub gist API to pull down my gists, and part of what I want to do is include the embedding functionality into my page. The problem is Mustache seems to not want to have anything to do with my dynamic script tag.
For example, this works fine:
<div class="gist-detail">
{{id}} <!-- This produces a valid Gist ID -->
</div>
Additionally, this works perfect:
<div class="gist-detail">
<script src='http://gist.github.com/1.js'></script> <!-- Produces the correct embed markup with Gist ID #1 -->
</div>
If I try to pull these together, something goes terribly wrong:
<div class="gist-detail">
<script src='http://gist.github.com/{{id}}.js'></script> <!-- Blows up! -->
</div>
Chrome Inspector shows this:
GET https://gist.github.com/%7B%7Bid%7D%7D.js 404 (Not Found)
... which looks like to me something is weird with escapes or whatnot, so I switch over to the raw syntax:
<div class="gist-detail">
<script src='http://gist.github.com/{{{id}}}.js'></script> <!-- Blows again! -->
</div>
And I get the same result in Inspector:
GET https://gist.github.com/%7B%7B%7Bid%7D%7D%7D.js 404 (Not Found)
How do I get the correct values to embed in the script tag?
EDIT
I am injecting the template as follows (in document.ready:
function LoadGists() {
var gistApi = "https://api.github.com/users/<myuser>/gists";
$.getJSON(gistApi, function (data) {
var html, template;
template = $('#mustache_gist').html();
html = Mustache.to_html(template, {gists: data}).replace(/^\s*/mg, '');
$('.gist').html(html);
});
}
The actually template is inside of a ruby partial, but it is wrapped in a div (not a script tag, is that a problem?) (that's hidden):
<div id="mustache_gist" style="display: none;">
{{#gists}}
<!-- see above -->
{{/gists}}
</div>
I assume a div is ok rather than a script because in either case, I'm pulling the .html(). Is this a bad assumption?
To avoid automatic escaping in Mustache use {{{token}}} instead of {{token}}.
It seems like your template is in HTML and trying to retrieve the template using html() results in a pre-URL-escaped template to be returned. Try placing your template inside a <script type="text/html"> tag instead.
When you embed your template inside an HTML element that excepts more HTML elements as children, it may get processed by the browser as HTML. Escaping may occur. By using a <script> tag with a non-script content type, you're basically telling the browser not to touch your template.
It looks like your script is getting requested before Mustache has a chance to update the src property. What you want to do is define the template in a way that it's not parsed as part of the DOM. A common approach is to define your template inside of a <textarea> tag. This will preserve formatting and prevent character escaping.
<textarea id="gist-detail-template" style="display:none">
<script src='http://gist.github.com/{{id}}.js'></script>
</textarea>
Now, to instantiate the template:
var template = $('#gist-detail-template').val();
var html = Mustache.to_html(template, yourTemplateData);
Here's an official example: http://mustache.github.com/#demo