How to set a Symfony2 path to Jeditable plugin - symfony

I'm trying to use Jeditable plugin for javascript. Here is the code (I took it from here):
In a .js file:
$('.edit').editable(function (value, settings) {
var data = {};
data[this.id] = value;
data["_token"] = "{{form._token.vars.value}}";
$.post("{{ path('edit_category', { 'id': cat.id}) }}", data);
return(value);
}, {
indicator:'Saving...',
tooltip:'Click to edit',
cancel:'Cancel',
submit:'Save'
});
This isn't working, it says that
No route found for "POST /{{ path('edit_category', { 'id': cat.id}) }}"
which I understand, because I have no idea how to pass the id parameter to the path (cat.id).
This is the way I'd do the edit only with Symfony in a template file:
<a href="{{ path('edit_category', { 'id': cat.id}) }}">
<i class="icon-pencil right-spacer"></i>
</a>
Any help will be appreciated! Thanks in advance!

The expression {{ path() }} is a twig expression, so it must be parsed by the twig template parser. Javascript files are usually not parsed.
You have some options on how to work around this. One idea is to inline your javascript code into your twig template. Of course that's not suitable for big code blocks and not very clean.
A better approach is to store the pathes in a variable in your layout twig template:
<script>
var token = "{{form._token.vars.value}}";
var path = "{{ path('edit_category', { 'id': cat.id}) }}";
</script>
In your js file, you only use the variables:
data["_token"] = token;
$.post(path, data);
Of course you might need to tweek that code if you have many pathes or variables.

Related

Timber how to implement get_current_url wp

Ive been using Wordpress for more than a year now. But I was stuck with the implementation of Timber twig framework get the current URL. I tried these codes below codes but no luck,.
{{ site.url.current }}
{{ app.request.getRequestUri() }}
Twig templates engine: get current url
Have you tried:
URLHelper::get_current_url()
Doc: https://timber.github.io/docs/reference/timber-urlhelper/#get_current_url
So, you should be able to feed this as a variable into your template.
Or if you want to get a step further and extend Timber's Twig i.e. creating a filter or function like:
$twig->addFilter(new \Twig_SimpleFilter('is_current_url', function ($link) {
return (URLHelper::get_current_url() == $link) ? true : false;
}));
Which should bring things down to:
{{ 'http://example.org/2015/08/my-blog-post' | is_current_url }}
BTW: Internally, get_current_url() returns: $_SERVER['HTTP_HOST']/$_SERVER['SERVER_NAME'] + $_SERVER["REQUEST_URI"]
Adding ['current_url'] in functions.php under add_to_context function worked for me:
public function add_to_context($context)
{
// $context['foo'] = 'bar';
$context['current_url'] = Timber\URLHelper::get_current_url();
$context['site'] = $this;
return $context;
}
You then will be able to use it globally in your twig templates:
<pre>
Current Url: {{ dump(current_url) }}
</pre>

Using twig translations inside Moustache inside Twig

I have a moustache template inside my twig template. I use the moustache template in javascript and it contains some text and JS variables.
{# _partial.html.twig #}
{% verbatim %}
<script id="insuranceOptionTpl" type="text/template">
{{ #. }}
<strong>My template is {{ adjective }}</strong>
{{ /. }}
</script>
{% endverbatim %}
Now I need to internationalize this page but my twig translations won't work inside verbatim. Is there any elegant ways to do that? I will probably have many different texts to translate, so ending and starting a new verbatim block all the time is not ideal.
By removing the verbatim block and by customizing Twig delimiters to be differents than Mustache ones, replacing {{ and }} by [[ and ]] for example (as explained in Twig doc), you'll be able to use Twig and Mustache in the same template:
$twig = new Twig_Environment();
$lexer = new Twig_Lexer($twig, array(
'tag_comment' => array('{#', '#}'),
'tag_block' => array('{%', '%}'),
'tag_variable' => array('[[', ']]'),
'interpolation' => array('#{', '}'),
));
$twig->setLexer($lexer);
As most of your templates are already in Twig, you can change Mustache delimiters instead:
$(document).ready(function () {
var output = $("#output");
var template = $("#insuranceOptionTpl").html();
//Custom tags for Mustache
var customTags = [ '[[', ']]' ];
Mustache.tags = customTags;
// render string
var data1 = "Hello world!";
var html = Mustache.render(template, data1);
output.append(html);
});

Meteor: Querying a collection based on a URL parameter

I am trying display the unique profile of a babysitter (i.e: babysitter username, city, postal code, etc ... ) from a schema/collection called "Babysitters" .
The URL correctly contains the babysitter unique _id, say:
http://localhost:3000/test/PqMviBpYAmTA2b5ec
but I don't manage to retrieve all the other fields.
meteor question - screenshot
I have tried querying the MongoDB in two files: routes.js and the template test.js
1) in routes.js
Router.route('/test/:_id', {
name: 'test',
data: function () {
return Babysitters.findOne({ _id: this.params._id });
}
});
2) in test.js
Template.test.helpers({
data: function () {
//sitterusername = this.params.sitterusername;
//console.log(this.params._id );
return Babysitters.findOne( { _id: this.params._id });
}
});
the html file: test.html
<template name="test">
{{#with data}}
<ul>
<li><img src="/" {{photourl}} height="100" width="100" ></li>
<li>Babysitter username: {{ sitterusername }}</li>
<li>Presentation: {{ presentation }}</li>
<li>City: {{ city }}</li>
<li>Postal Code: {{ postalcode }}</li>
<li>Mother tongue: {{ mothertongue }}</li>
<li>Languages spoken {{ languagesspoken }}</li>
<li>Experience {{ experience }}</li>
<li>Homework help: {{ homeworkhelpavailable }}</li>
<li>Hourly wages: {{ hourlywages }} €/h</li>
</ul>
{{/with}}
</template>
I have tried all sorts of ways but the Collection fields never appear in the HTML file.
Thanks for your help, a newbie here.
K.
Most likely you are not publishing all Babysitters to the client so your .findOne() returns nothing.
This is a common router pattern where you want to display a single document which is not normally published. A good way to solve this in i-r is to waitOn a subscription to the individual document:
waitOn: function(){
return Meteor.subscribe('oneBabysitter', this.params._id);
}
On the server, publish:
Meteor.publish('oneBabysitter',function(_id){
return Babysitters.find(_id);
});
Note that even though this publication is only going to return a single document you still have to do a .find() and not a .findOne() because publications need to return a cursor or array of cursors, not objects.

symfony2.7, bloodhound, typeahead not showing autocomplete

i'm trying to use typeahead with symfony 2.7 for database search using LIKE. I've read the documentation for typeahead and based on the examples from their website i put togther a small example to see how it works. Since i have about 1300 entries in the table where i perform search i generated a json file with all the entries for performance.
The problem is that typeahead doesn't show any info from remote or from prefetch and i don't understand why it doesn't work because i didn't make too many changes to the original code from the examples. For the moment the generated result contains dummy data from the examples page because i was thinking there is something wrong with the results returned from remote. Maybe i'm missing something and i can't see the solution.
I checked the console and i don't get any errors, bloodhound is loaded before typeahead both are loaded fine and the js file is loaded after them and it shows the content.
Javascript File:
var url = Routing.generate('ajax_search', {name: 'query'});
// Trigger typeahead + bloodhound
var products = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: '/json/result.json',
remote: {
url: url,
wildcard: 'query'
}
});
products.initialize();
$('#products_forms .typeahead').typeahead({
name: 'product',
displayKey: 'value',
source: products.ttAdapter()
});
the html test file
{% extends '::base.html.twig' %}
{% block body %}
<div class="col-sm-10" id="product">
<input type="text" placeholder="Product" id="product" name="product" class="form-control typeahead">
</div>
{% endblock %}
The dummy file generated from php
cat result.json
{"stateCode": "CA", "stateName": "California"},
{"stateCode": "AZ", "stateName": "Arizona"},
{"stateCode": "NY", "stateName": "New York"},
{"stateCode": "NV", "stateName": "Nevada"},
{"stateCode": "OH", "stateName": "Ohio"}
seems it works like this:
javascript:
$(document).ready(function() {
var url = Routing.generate('ajax_search', {name: 'WILDCARD'});
// Trigger typeahead + bloodhound
var products = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
identify: function(obj) { return obj.team; },
prefetch: 'json/result.json',
remote: {
url: url,
wildcard: 'WILDCARD',
}
});
products.initialize();
$('#products_forms .typeahead').typeahead({
minLength: 3,
highlight: true
},
{
name: 'product',
display: 'team',
source: products.ttAdapter()
});
});

Translations in JS files with Symfony2

I'm currently developing an applications that will need to use translations from my JavaScripts.
The bundle BazingaJsTranslationBundle seems to be good, but after I tried it I don't think it fits my needs. It generates all the translations for all my application's bundles. It can be heavy to load.
Do you know other bundles or tricks for that ?
Thank you for your help.
I had similar problem (large translation files) with BazingaJsTranslationBundle and I simplify this by:
#config.yml
bazinga_expose_translation:
default_domains: [ jsonly ]
locale_fallback: "%locale%"
create simple html twig to store your js variables and bazing expose them from this files
{# jsOnleVariables.html.twig #}
{% set var1 = 'Welcome'|trans({},'jsonly') %}
{% set var2 = 'Bye'|trans({},'jsonly') %}
dump variables
php app/console bazinga:expose-translation:dump web/js
and in your layout include only wanted variables
{# layout.html.twig #}
<script src="{{ asset('bundles/bazingaexposetranslation/js/translator.js') }}" type="text/javascript"></script>
{% if app.request.locale == 'pl' %}
<script src="{{ asset('js/i18n/jsonly/pl.js') }}" type="text/javascript"></script>
{% else %}
<script src="{{ asset('js/i18n/jsonly/en.js') }}" type="text/javascript"></script>
{% endif %}
Depending on your exact needs and circumstances, a simple object in json format can be a good enough dictionary. For example like this:
var dict = {
TextIdWelcome : "Welcome",
TextIdGoodBy : "Good by"
}
A usage example:
var elem = document.getElementById("WelcomeTag");
elem.innerHtml = dict["TextIdWelcome"];
You can generate such json object on your server side for the actual language selected on client side and you can retrieve it by your favourite method (jquery, XMLHttpRequest, etc), and just assign it to this dict variable.
If you need sentences with runtime dependent values in it, a simple basic trick might fit your needs. Let use some markup like %0, %1, etc in the translated text.
var dict = {
TextIdWelcome : "Welcome %0",
TextIdGoodBy : "Good by %0"
}
function tr(textId, runTimeValue1, runTimeValue2){
var text = dict[textId];
if(runTimeValue1 !== undefined)
text = text.replace("%0", runTimeValue1);
if(runTimeValue2 !== undefined)
text = text.replace("%1", runTimeValue2);
return text;
}
So a usage example:
var userName = "Jhon";
var elem = document.getElementById("WelcomeTag");
elem.innerHtml = tr("TextIdWelcome", userName);
Please note that this solution lacks several refined tricks (escaping markups, variable number of runtime values, efficient replace algorithm, etc), but in simple everyday cases this could be good enough. This trick is also very simple (so you can easily enhance it to your needs) and you can control 100% how exactly it should handle the dictionary. You can of course control when and what dictionary to load into the dict variable.

Resources