Concatenate twig path in javascript string - javascript

I'm working on a PHP site with Slim and Twig-View. Within this site I'm working on live search with Ajax. The idea is for the user to search for a string and for search results to appear as the user types. Everything is working fine so far. I'm able to get the results and render them with the appropriate image and text. The problem comes when creating the link for each result. With Slim Twig-view, when you create a link, you use the path_for() function:
{{ path_for('episode', { 'show_slug': path, 'episode_slug': episode }) }}';
In this case, the values for path and episode are being generated by Javascript. The problem is that if I try the following:
var path = '{{ path_for('episode', { 'show_slug': results[i].showPath, 'episode_slug': results[i].url }) }}';
I have also tried using double quotes:
var path = "{{ path_for('episode', { 'show_slug': results[i].showPath, 'episode_slug': results[i].url }) }}";
The resulting link is myurl/shows// instead of myurl/shows/show-slug/episode-slug
So, path_for() is actually working, but it's not reading the values for results[i].showPath and results[i].url. It looks like this is just a concatenation issue, but I can't figure out how to do it correctly.

Related

Django | JS variable inside dynamic URL

I'm trying to pass a javascript variable inside a dynamic url using Django. I have the following path
path('task-update/<str:pk>/', updateTask, name='task-update'),
I'm able to retrieve the "Task" fields I created (id, title, description, ...) depending on what task I select inside the HTML (this is done using AJAX and the Django-REST Framework). However, I'm having some trouble on rendering javascript values inside dynamic urls
var url = `{% url 'task-update' pk=${activeItem.id} %}`
The ${activeItem.id} is where I'm having some trouble, I tried assigning it to a variable and passing that into the URL but it doesn't work.
A workaround I've been using is
var url = `http://127.0.0.1:8000/task-update/${activeItem.id}/`
however I'd like to use django's template tags
After searching for quite a bit this was the best neat-looking solution I found (also the only one): django-js-urls.
Just pip install django-js-urls and add 'js_urls' to your INSTALLED APPS.
Afterwards add simply add JS_URLS to your settings.py file and put the names of the paths you'd like to use. In my case I only added task-update, it looks something like this
JS_URLS = (
'task-update',
)
Then, all you need to do is add the following in the URLs root module
from js_urls.views import JsUrlsView
urlpatterns = [
# other urls
url(r'^js-urls/$', JsUrlsView.as_view(), name='js_urls'),
]
And include the following js in the template
<script src="{% url 'js_urls' %}" type="text/javascript"></script>
URLs can be used using the window.reverse function
var url = window.reverse('task-update', { pk: activeItem.id });
I found a trick that might work under most circumstances:
var url = "{% url 'task-update' pk=12345 %}".replace(/12345/, ${activeItem.id});
It's clean, and it doesn't break DRY principle.

set twig variable from json array

As twig renders prior to any javascript, I'm running into what feels like a minor problem.
I need to set a variable in twig that I receive from JSON array, but I'm running into some problems, and I feel like this should be simple.
The data is fed to twig through symfony through a json array, and renders different messages depending on one element in the array; this part works without trouble.
I am able to print the output to the twig file; that works fine. The problem is that I'm having a hard time setting this to a twig variable so that I can use it in a few places.
This works fine:
$('.id').html(items[0].id);
and prints out to the twig here correctly:
<div class="id"></div>
I tried to do do something like this:
{% set requestid = '<div class="id"></div>' %}
{{ requestid }}
But as expected this simply rendered the HTML without the value.
I've been attempting to do something like this:
In the twig I have this:
{% set requestid = "request_holder" %}
{{ requestid }}
And in the jquery I have something like this:
var reqid = items[0].id;
reqid.replace("request_holder",reqid);
I also attempted something like this
var request_id = items[0].id;
window.location = request_id.replace("request_holder",request_id)
I feel like I'm missing a small piece.
**Edit for clarity **
The JSON array is being parsed by jquery.
I have the value of items[0].id
Additional edit here - to make it clear that I was confused: cleaning up a little so as not to send future readers down the wrong path
I believe[d] that the variable needs to be assigned in the javascript because the twig, which is php, is generated prior to the javascript.
I have been attempting to generate the twig in the javascript to no avail.
Here's what I have been attempting:
var requestitem = items[0].id;
$('.id').html("{% set requestId = " + requestitem + " %} <br/> {{ requestId }}");
This defines requestId as a string and is only returning + requestitem + onto the page.
When I attempt this (without the quotations)
var requestitem = items[0].id;
$('.id').html("{% set requestId = requestitem %} <br/> {{ requestId }}");
The twig does not recognize requestitem at all
I have attempted quoting out the twig brackets (e.g. "{" + "%" etc) but this of course only prints them onto the page and does not interpret them.
Twig processes on the server side. It takes variables and renders them as HTML and text. What gets displayed in the browser is just HTML / text / and Javascript. So your set requestid = "request_holder" and {{ requestid}} are just turned to text before they get to the browser.
After that, you have HTML and text on the front end which Javascript can interact with. If you need this id to change on the front end, it needs to be done in Javascript.
What are you using the id to do?
Thanks to the hint from ASOlivieri, I was able to realize what I was doing wrong. I'm putting this here in case anyone comes across this. I was simply looking for a way to create a variable and make it reusable (I didn't go into details as that seemed extraneous).
The data was only available in the JSON array, so any attempt to write it to a twig file would fail, quite simply because it had already been converted to HTML, so I was forced to find another solution,
I was able to keep the variable in a javascript as I had it before
var request_item = items[0].id;
As my original goal was to get the value to update the application through php, I simply needed to use this variable in an AJAX call, and pass it through the path I had wanted to use in twig. Here's a brief summary:
$('#mark-received').click(function()
{
var requestURL = "{{ path('my_path') }}";
jQuery.ajax({
url: requestURL,
type: 'GET',
data: {'id' : request_item},
success: function success(data, text, xhr){
$('#mark-received').addClass('hidden');
$('#received-canceled').removeClass('hidden');
$('header > .alerts').append( $('<div>Success Message</div>').addClass('alert alert-success'));
},
error: function error( xhr, status, err){
$('header > .alerts').append( $('<div>There is a problem. <div class="close">x</div></div>', err).addClass('alert alert-danger'));
}
})
});

set jinja2 url_for as an href in getJSON callback

I am working inside a jquery, getJSON callback function using flask as my web framework.
I am trying to set the link desination for a dynamically created dom element. I want to set it to the jinja2 code for url_for. So, I would like to do something like this:
a.href ="{{ url_for('write_response', id=".concat(data.libArticles[i].id.toString(), ") }}");
I have had the worst time doing this. First, it would not recognize the "{{" and "}}" strings, removing them, opening quotes and doing other weird stuff because of those characters. Finally, by doing this:
var url1 = "{url_for('write_response', id=".concat(data.libArticles[i].id.toString(),")}");
var url2 ="{".concat(url1, "}");
a.href = url2;
it finally accepted the string with two instances of "{", so it accepted "{{somethig}}"
This still did not work and instead, when the link is clicked, it redirects to the following and fails :
http://localhost:5000/write_response/%7B%7Burl_for('write_response',%20id=3)%7D%7D
Does anyone know how to do this?
Your mixing up your python and javascript. Your first attempt failed, because your trying to execute javascript inside python. What's actually happening is everything, including the ".concat is being treated as the value for your id. Your second attempt is even more confused.
It's worth remembering that the python code gets executed on the server and then sent to the browser, the javascript gets executed after the fact in the browser. So the python/jinja code can't possibly know about the value of a javascript variable.
I think you should be able to do something like the following to get it to work:
var url = "{{ url_for('write_response') }}";
var id = encodeURIComponent(data.libArticles[i].id.toString());
url += '?id='+id;
Everything inside the set of {{ }} is considered jinja code, seperate from whatever is going on around it in the file. this should translate into the following in the browser:
var url = "/write-response";
var id = encodeURIComponent(data.libArticles[i].id.toString());
url += '?id='+id;
which should get you something like /write-response?id=12345
The encodeURLComponent(..) call just makes sure the value is url safe.

Twig JS Inline template unable to parse

I'm new to Twig.js templating and having some trouble getting it to render some JSON correctly. I'm using jQuery to pull a JSON result from Youtube and passing it to an inline Twig template. Everything's working fine except within my template the actual text I need to extract from the JSON is under item.title.$t and the $ seems to be throwing it off. I get the error Unable to parse '$t' at template position0.
My full function is as follows:
$.getJSON('http://gdata.youtube.com/feeds/api/videos?q=stack+overflow&max-results=5&&v=2&alt=json', function(data){
var template = twig({
id: 'videos',
data: '{% for item in feed.entry %}<h1>{{ item.title.$t }}</h1>{% endfor %}'
});
var postsHTML = twig({ ref: "videos" }).render(data);
// Display the rendered template
document.getElementById("videos").innerHTML = postsHTML;
});
Is there a way to escape strange characters such as $ within a template? I can't find reference to such an ability in the documentation. I know the data is getting read in correctly as I can render the title object, just not it's $t propoerty. Thank you for your help!
After some more tweaking I tried accessing the property as an array again and it worked. See below:
'{% for item in feed.entry %}<article><header><h1>{{ item.title[\'$t\'] }}</h1></header></article>{% endfor %}'

Django: reverse parametrized url in JavaScript

let's say one of my urlpatterns looks like this.
url('^objects/update/(?P<pk>\d+)$', views.UpdateView.as_view(), name = 'update-object'),
I need to redirect user to the update page depending on the selected object (the list of objects is populated using Ajax). So I'd like to pass that named url pattern to the JavaScript, in order to build the actual url on the client side.
Example of what I want to achieve:
pass the name 'update-objects' to the function
get the actual url pattern, replace (?P<pk>..) with {pk}
pass the result to the javascript, resulting in : objects/update/{pk}
any tips?
thanks
to make it more clear: at the moment of rendering, I can't do url reverse because the PK is not known yet. I need to make kind of javascript-urlpattern which will later be converted to the real url (i.e. my JS code will replace {pk} part with the actual pk value)
The actual URL reversing must happen on the server side. There are several ways to do this, and the most elegant of these probably depends on how exactly your script and markup are set up for this. One thing I've done recently is to attach the URL to a logical element using HTML5 data attributes, which are easy to retrieve using jQuery. If you're not using jQuery, I'll leave it up to you to translate to pure JS. You haven't provided any code or specifics for your client-side, so I'm kind of shooting in the dark here, but maybe this will give you the idea:
Django HTML template:
<ul class="object-list">
{% for object in objectList %}
<li data-update-url="{% url update-objects object.pk %}">object.name</li>
{% endfor %}
</ul>
JS:
$('.object-list').on('click', 'li' function () {
var updateUrl = $(this).data('update-url')
...
});
It sounds like you need to make an additional ajax call once the object has actually been selected. Don't try and second guess your url.conf by trying to work out the url on the client side - you'd just be making trouble for yourself later. Wait till you can get a pk, then use django's reverse function to give you your url (doing anything else violates DRY).
How about creating a simple view that returns the url -
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseBadRequest
def get_url(request):
if request.is_ajax() and request.method == 'POST':
obj_id = request.POST['obj_id']
url = reverse('object-update', kwargs{'pk': obj_id})
return HttpResponse(obj_id)
return HttpResponseBadRequest()
Then write a javascript function that gets the url using an ajax call to your new view and then redirects. You'd call this function as soon as the object's been selected. I would suggest using JQuery to do this, pure javascript will require you to write more code, and probably write browser specific code (depending on your target). Also it supports dealing with django's csrf protection (you'll need to implement this for ajax calls if you haven't already).
var redirect = function(obj) {
$.ajax({
url: '/your-get-url-view/',
method: 'post',
data: {'obj_id': obj},
success: function(url){
window.location = url;
}
});
}
I'm afraid I don't know how you're getting from the selected object to the pk (For simplicity I've assumed it's available to the redirect function) - you may have to do some processing in the view to get there.
I haven't tested the above code, but it should give you an idea of what I'm suggesting.
Try this one:
Reverse method for generating Django urls
https://github.com/mlouro/django-js-utils
One more
https://github.com/Dimitri-Gnidash/django-js-utils
If you have a URL that only has one PK field in it, you could resolve it with any number (e.g. 0), then substitute the number as required.
In my scenario my URL had a pk then an upload_id, so I had to replace on the right most instance of a 0, with <upload_id>, which the JS would replace this string occurance as required:
detele_url_upload_id_0 = reverse(f'{APP_NAME}:api_upload_delete', args=[pk, 0])
prefix, suffix = detele_url_upload_id_0.rsplit('0', 1)
context['generic_delete_url'] = prefix + '<upload_id>' + suffix
Then in the JS:
const deleteUrl = genericDeleteUrl.replace('<upload_id>', uploadId)

Categories