How To Format the Currency symbol in Twig - symfony

what i need
i need to show the currency code .
like usd : $.
i have used script
<script type="text/javascript">
var cod=new Array();
var sym=new Array();
cod[0]='ALL';sym[0]='Lek';cod[1]='USD';sym[1]='$';cod[2]='AFN';sym[2]='؋';cod[3]='ARS ';sym[3]='$';cod[4]='AWG';sym[4]='ƒ';cod[5]='AUD';sym[5]='$';cod[6]='AZN';sym[6]='ман';cod[7]='BSD;';sym[7]='$';cod[8]='BBD';sym[8]='$';cod[9]='BYR';sym[9]='p.';cod[10]='BEF';sym[10]='₣';cod[11]='BZD';sym[11]='BZ$';cod[12]='BMD';sym[12]='$';cod[13]='BOB';sym[13]='$b';cod[14]='BAM';sym[14]='KM';cod[15]='BWP ';sym[15]='P';cod[16]='BGN';sym[16]='лв';cod[17]='BRL';sym[17]='R$';cod[18]='BRC';sym[18]='₢';cod[19]='GBP';sym[19]='£';cod[20]='BND';sym[20]='$';cod[21]='KHR';sym[21]='៛';cod[22]='CAD ';sym[22]='$';cod[23]='KYD';sym[23]='$';cod[24]='CLP';sym[24]='$';cod[25]='CNY';sym[25]='元';cod[26]='COP ';sym[26]='$';cod[27]='CRC ';sym[27]='₡';cod[28]='HRK';sym[28]='kn';cod[29]='CUP';sym[29]='₱';cod[30]='CYP';sym[30]='£';cod[31]='CZK ';sym[31]='Kč';cod[32]='DKK ';sym[32]='kr';cod[33]='DOP';sym[33]='RD$';cod[34]='XCD ';sym[34]='$';cod[35]='EGP';sym[35]='£';cod[36]='SVC ';sym[36]='$';cod[37]='GBP ';sym[37]='£';cod[38]='EEK';sym[38]='kr';cod[39]='EUR';sym[39]='€';cod[40]='XEU ';sym[40]='₠';cod[41]='FKP';sym[41]='£';cod[42]='FJD';sym[42]='$';cod[43]='FRF';sym[43]='₣';cod[44]='GHC';sym[44]='¢';cod[45]='GIP ';sym[45]='£';cod[46]='GRD ';sym[46]='₯';cod[47]='GTQ';sym[47]='Q';cod[48]='GGP';sym[48]='£';cod[49]='GYD';sym[49]='$';cod[50]='NLG ';sym[50]='ƒ';cod[51]='HNL';sym[51]='L';cod[52]='HKD';sym[52]='HK$';cod[53]='HKD ';sym[53]='圓';cod[54]='HKD ';sym[54]='圓';cod[55]='HKD ';sym[55]='元';cod[56]='HUF';sym[56]='Ft';cod[57]='ISK';sym[57]='kr';cod[58]='INR ';sym[58]='Rs';cod[59]='IDR ';sym[59]='Rp';cod[60]='IRR';sym[60]='﷼';cod[61]='IEP ';sym[61]='£';cod[62]='IMP';sym[62]='£';cod[63]='ILS';sym[63]='₪';cod[64]='ITL';sym[64]='₤';cod[65]='JMD';sym[65]='J$';cod[66]='JPY ';sym[66]='¥';cod[67]='JEP ';sym[67]='£';cod[68]='KZT ';sym[68]='лв';cod[69]='KPW ';sym[69]='₩';cod[70]='KRW ';sym[70]='₩';cod[71]='KGS ';sym[71]='лв';cod[72]='LAK ';sym[72]='₭';cod[73]='LVL ';sym[73]='Ls';cod[74]='LBP ';sym[74]='£';cod[75]='LRD ';sym[75]='$';cod[76]='CHF ';sym[76]='CHF';cod[77]='LTL ';sym[77]='Lt';cod[78]='LUF ';sym[78]='₣';cod[79]='MKD ';sym[79]='ден';cod[80]='MYR ';sym[80]='RM';cod[81]='MTL ';sym[81]='Lm';cod[82]='MUR ';sym[82]='₨';cod[83]='MXN ';sym[83]='$';cod[84]='MNT ';sym[84]='₮';cod[85]='MZN ';sym[85]='MT';cod[86]='NAD ';sym[86]='$';cod[87]='NPR ';sym[87]='₨';cod[88]='ANG ';sym[88]='ƒ';cod[89]='NLG ';sym[89]='ƒ';cod[90]='NZD ';sym[90]='$';cod[91]='NIO ';sym[91]='C$';cod[92]='NGN ';sym[92]='₦';cod[93]='KPW ';sym[93]='₩';cod[94]='NOK ';sym[94]='kr';cod[95]='OMR ';sym[95]='﷼';cod[96]='PKR ';sym[96]='₨';cod[97]='PAB ';sym[97]='B/.';cod[98]='PYG ';sym[98]='Gs';cod[99]='PEN ';sym[99]='S/.';cod[100]='PHP ';sym[100]='Php';cod[101]='PLN ';sym[101]='zł';cod[102]='QAR ';sym[102]='﷼';cod[103]='RON ';sym[103]='lei';cod[104]='RUB ';sym[104]='руб';cod[105]='SHP ';sym[105]='£';cod[106]='SAR ';sym[106]='﷼';cod[107]='RSD ';sym[107]='Дин.';cod[108]='SCR ';sym[108]='₨';cod[109]='SGD ';sym[109]='$';cod[110]='SKK ';sym[110]='SIT';cod[111]='EUR ';sym[111]='€';cod[112]='SBD ';sym[112]='$';cod[113]='SOS ';sym[113]='S';cod[114]='ZAR ';sym[114]='R';cod[115]='KRW ';sym[115]='₩';cod[116]='ESP ';sym[116]='₧';cod[117]='LKR ';sym[117]='₨';cod[118]='SEK ';sym[118]='kr';cod[119]='CHF ';sym[119]='CHF';cod[120]='SRD ';sym[120]='$';cod[121]='SYP ';sym[121]='£';cod[122]='TWD ';sym[122]='NT$';cod[123]='THB';sym[123]='฿';cod[124]='TTD';sym[124]='TT$';cod[125]='TRY';sym[125]='YTL';cod[126]='TRL';sym[126]='₤';cod[127]='TVD ';sym[127]='$';cod[128]='UAH ';sym[128]='₴';cod[129]='GBP ';sym[129]='£';cod[130]='USD ';sym[130]='$';cod[131]='UYU ';sym[131]='$U';cod[132]='UZS ';sym[132]='лв';cod[133]='VAL ';sym[133]='₤';cod[134]='VEB ';sym[134]='Bs';cod[135]='VND ';sym[135]='₫';cod[136]='YER ';sym[136]='﷼';cod[137]='ZWD ';sym[137]='Z';
function list(index)
{
var con=document.getElementById('sym');
if(index==-1)
{
con.innerHTML="";
return;
}
con.innerHTML=sym[index];
}
</script>
<script type="text/javascript">
count=cod.length;
for(i=0;i<count;i++)
document.write("<option value="+i+">"+cod[i]+"</option>");
</script>
</select>
Twig code
{% set currency= '' %}
{% for key,value in temp %}
{% set currency= value %}
<td width="12%" id ="cod" class="aligncenter">{{ value.amount }}<p class=sym>{{ currency}}</p> </td>
i need like 20 $.
i need to convert currency convert through java script.
i have tried but its not laoding in twig file.

If you have list of currency codes you can just go through them and call:
public function getCurrenciesAction()
{
$currencies = array('EUR', 'USD'); //here you need to retrieve your currencies list
$symbols = array();
foreach ($currencies as $currency) {
$symbols[$currency] = $symbol = Intl::getCurrencyBundle()->getCurrencySymbol($currency);
}
return new JsonResponse($symbols);
}
You can then generate JSON array from the whole list and retrieve it in JavaScript via AJAX request.

There is an issue with "document.getElementById('sym');", as there aren't any "sym" element
Change :
<p class=sym>
to
<p id="sym">

Related

show/hide dynamic content with parameter in Wordpress

I am trying to create a second hidden page within my post which will be shown on specific parameters.
Here is the code I am using in singe.php
<!-- Default Dynamic Section -->
<div id="default-content" class="dynamic-content">
<?php the_content(); ?>
</div>
<!-- Dynamic Section 1 -->
<div id="downloadlinks" class="dynamic-content">
<?php the_title(); ?>
</div>
content of section 1 is just for an example.
this is javascript jquery code,
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
// Parse the URL parameter
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// Give the parameter a variable name
var dynamicContent = getParameterByName('download');
$(document).ready(function() {
// Check if the URL parameter is apples
if (dynamicContent == 'links') {
$('#downloadlinks').show();
}
// Check if the URL parmeter is empty or not defined, display default content
else {
$('#default-content').show();
}
});
</script>
I need to know, do I am going well. Is there any good way to do that?

can i pass my php code to twig code of timber

I would like to know if I can convert any types of PHP code to twig, what I want to know is, for example, whether I can pass the code.
<?php
if (ICL_LANGUAGE_CODE == 'in'):?
to
{{ lang.en }}
Is there a way to add any PHP code and turn it into a twig and recognize it?
I use the Timber template for WordPress.
There is a good way to pass your functions (more correctly, register the function to Twig).
Using Timber Hook: timber/twig
There is a class in filter hook timber/twig could help us pass functions to Twig. It calls Timber\Twig_Function.
new Timber\Twig_Function(
'function_name_that_will_be_called_in_Twig',
'function_name_in_php'
);
// OR
new Timber\Twig_Function(
'function_name_that_will_be_called_in_Twig',
function( $input ) {
// anonymous function is ok too.
}
);
functions.php
add_filter( 'timber/twig', 'add_to_twig' );
function hello_in_php( $name = 'world' ) {
$hello = 'Hello ';
$hello .= $name;
return $hello;
}
function add_to_twig( $twig ) {
$func = new Timber\Twig_Function('hello', 'hello_in_php');
$filter = new Timber\Twig_Function('introduce', function( $name ) {
return "I'm ${name}!";
});
$twig->addFunction($func); //Registering a pre-defined function
$twig->addFunction($filter); //Registering a filter function
return $twig;
}
index.twig:
<p id='a'>{{ hello() }}</p>
<p id='b'>{{ hello('who?') }}</p>
<p id='c'>{{ "Batman"|introduce }}</p>
Result is:
<p id='a'>Hello World</p>
<p id='b'>Hello who?</p>
<p id='c'>I'm Batman!</p>
Source: https://timber.github.io/docs/guides/extending-timber/#adding-functionality-to-twig
You mean something like this comparison ?
{% if constant('ICL_LANGUAGE_CODE') == 'en' %}
{# your output here #}
{% endif %}

Symfony Twig : get Object property with a variable property

Symfony 3.0 :
In my project, I have many entities which contain more than 50 fields, so for the twig which shows every entity, I decided to automate the display of the 50 fields by a simple loop.
First problem: how to get entity's all fields names, I resolved this by creating a custom twig filter:
<?php
// src/HomeBundle/Twig/HomeExtension.php
namespace HomeBundle\Twig;
class HomeExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('object_keys', array($this, 'getObjectKeys')),
);
}
public function getObjectKeys($object)
{
//Instantiate the reflection object
$reflector = new \ReflectionClass( get_class($object) );
//Now get all the properties from class A in to $properties array
$properties = $reflector->getProperties();
$result=array();
foreach ($properties as $property)
$result[] = $property->getName();
return $result;
}
public function getName()
{
return 'app_extension';
}
}
?>
The second problem which generates the error right now is: how to access object properties within a loop:
{% for property in article|object_keys%}
<tr>
<th>
{{property|capitalize}}
{# that's work clean #}
</th>
<td>
{{ attribute(article,property) }}
{# that's generate the error #}
</td>
</tr>
{% endfor %}
The error :
An exception has been thrown during the rendering of a template
("Notice: Array to string conversion"). 500 Internal Server Error -
Twig_Error_Runtime
Finally, the error is fixed on the getObjectKeys method of the filter,
so when it returns an array that I create manually it works:
return array("reference","libelle");
But, when I send an array created within a loop => Error.
I dumped the two arrays in the twig, they were equivalents, but the second still generating an error.
Most likely one of your properties is returning an array rather than a simple string, integer, .... A solution here could be to store the value in a variable and check whether the stored value is an array. Depending on that check do something with the value or otherwise just output the variable
{% for property in article|object_keys%}
<tr>
<th>
{{property|capitalize}}
</th>
<td>
{% set value = attribute(article,property) %}
{% if value is iterable %}{# test if value is an array #}
{{ value | join(', ') }}
{% else %}
{{ value }}
{% endif %}
</td>
</tr>
{% endfor%}

twig automatic convert string to day

I want to convert a string value to day by tapping in a widget, e.g. 24 → 1
{% block convert_day %}
<td>{{ form_widget(form['crush']) }}</td>
<td><!-- displaying my value in day --></td>
{% endblock %}
No It doesn't work !
To be more clear ,I want to do something like that but just display number of days : http://www.convertworld.com/en/time/Days.html
{{ hourValue / 24 }}
Or, if you want to round the value to two decimal places:
{{ hourValue / 24 | number_format(2, ".", ",") }}
Documentation:
http://twig.sensiolabs.org/doc/templates.html#math
http://twig.sensiolabs.org/doc/filters/number_format.html
edit
Alternatively, you can put the precision into the form instance itself. When you create your form, you're probably doing something like this in your controller (or if the form has its own class, you're doing something similar in the buildForm() method of that class):
$form = $this->createFormBuilder($entity)
->add('name', 'text')
->getForm();
When you add your crush field, you can then specify the number of decimal places that should be represented on the form by including the precision option:
$form = $this->createFormBuilder($entity)
->add('name', 'text')
->add('crush', 'number', array('precision' => 3) )
->getForm();
The form will then round the value before inserting it into the database.
Documentation:
http://symfony.com/doc/current/reference/forms/types/number.html#precision
that's what I did ;
<script type="text/javascript">
function execute_time_ext(clicked) {
if (document.forms && document.forms['show_convert']) {
var from = document.forms['show_convert'].unit_from.value;
var elms = document.getElementsByName('unit');
var amount = document.forms['show_convert']['value'].value;
var to;
var amount_int = ['show_convert']['value'] - 0;
for (var i=0; i<elms.length; i++) {
to = elms[i].value;
convert(show_convert['value'], from, to, false, false);
}
var cookie = 'default_decimals';
if (getCookie(cookie) != decimals) {
setCookie(cookie, decimals, null, '/');
}
} else {
if (clicked) {
alert('Converter error. Conversion not supported by browser.');
}
}
}
execute_time_ext(false);
</script>
widget :
<div onkeyup="execute_time_ext(true)" onchange="execute_time_ext(true)"> {{ form_widget(form['value']) }} {% endblock %}
<div> <input id="value_4" type="hidden" value="365.25|0|4" name="unit"></div>
</div>

Handlebars helper for template composition

I have a Handlebar helper to invoke a template within a template,
the usage is this :
applyTemplate subTemplateId arg1=123 arg2="abc" ...
It is also possible to pass html content
{{# applyTemplate "tli" a=1 b="y"}}
... any content here will get passed to the sub template with {{content}}
{{/ applyTemplate }}
This jsFiddle illustrates how it works : http://jsfiddle.net/maxl/ywUjj/
My problem : I want the variables in the calling scope to be accessible
in the sub templemplate, in the jsFiddle, notice how {{topLevelVar}}
is not available.
Thanks
From this example i would say you can use fn to access the context in your helper method
http://yehudakatz.com/2010/09/09/announcing-handlebars-js/
applyTemplate: function(context, fn) {
for(var i=0, j=context.length; i < j; i++) {
buffer.push(fn(context[i]))
}
}
Where fn is the inner "template" part, and context the model that gets applied to it.
Starting from the solution on http://jsfiddle.net/dain/NRjUb/ we can achieve the same result but with inline templates as:
<script id="topLevel" type="text/x-handlebars-template">
{{# defTpl "test1"}}
La plantilla <b>diu</b> {{part}},{{../topLevelVar}}
{{/ defTpl }}
{{# each sub }}
Iplant-->{{eTpl "test1" part=this}}--fi plant<br>
{{/each}}
</script>
And registering the handlebars helpers like:
(function()
{
var h={};
Handlebars.registerHelper('defTpl', function(name, context){
// the subtemplate definition is already compiled in context.fn, we store this
h[name]=context.fn;
return "";
});
// block level /inline helper
Handlebars.registerHelper('eTpl', function(name, context){
if (!h[name]) return "Error , template not found"+name;
var subTemplate = h[name];
//if this isn't a block template , the function to render inner content doesn't exists
var innerContent = context.fn?context.fn(this):"";
var subTemplateArgs = $.extend({}, context.hash, {content: new Handlebars.SafeString(innerContent)});
return new Handlebars.SafeString(subTemplate(subTemplateArgs))
});
})();
And calling this with:
var _template = Handlebars.compile($('#topLevel').html());
$('body').append(_template({topLevelVar:123, content:"cascading",sub:[45,30,12]}));
Hope this helps :)
Add "../" before topLevelVar to access the parent context.
For example:
{{../topLevelVar}}
<script id="tli" type="text/x-handlebars-template">
<tr><td>{{a}}----> {{content}} <----- {{b}}</td></tr>
</script>
<script id="zaza" type="text/x-handlebars-template">
<table>
{{# applyTemplate "tli" a=1 b="y"}}<input type="text" value='a'>{{../topLevelVar}}{{/ applyTemplate }}
{{# applyTemplate "tli" a=2 b="z"}}<input type="text" value='b'>{{/ applyTemplate }}
</table>
</script>

Resources