how to pass javascript variable into liquid markup? - javascript

I have a value from JavaScript:
var customerID = document.getElementById("CustomerID").value;
Now I want query the firstName, lastName from module data, based on that customerID variable.
{module_data resource="customers" version="v3" fields="id,firstName,lastName,titleType,customerTypeId,ratingTypeId" skip="0" limit="10" order="lastName" collection="selected-data"}
{% for item in selected-data.items %}
{% if item.id == 10393092%}
document.getElementById("CAT_Custom_15").setAttribute("value","{{item.titleType.label}}") ;
document.getElementById("CAT_Custom_14").setAttribute("value","{{item.firstName}}");
document.getElementById("CAT_Custom_4").setAttribute("value","{{item.lastName}}");
{% endif %}
{% endfor %}
How should I write the where condition?
Whne I assign instant value that 10393092 in my code above. It is working fine. but I need assign the variable equal to item.id(like item.id == customerID). Anyone can help? Thank you so much

What you are asking for is not possible. Liquid generates a static page, which is then stored on your web server. When a user navigates to your site, the pre-generated page is sent to them. Then the JavaScript in it may execute. At this point, it is impossible to do anything in Liquid. You should be looking for a pure JavaScript solution.

Unfortunately you cannot do that. Reason is liquid is processed at server side and you will be fetching the content from the browser DOM using
var customerID = document.getElementById("CustomerID").value;
When the page loads, the content from server (for module_data) have already processed and after that the DOM elements will load resulting in no data passed to liquid if else condition.
At the moment there is no way to send javascript data to the server for module_data.

Related

How to use const values ​from JavaScript as an argument of Django Custom template tags and filters?

If I have custom filters and write {% load file_name %} into index.html, How to write:
<script>
const x = 10;
const y = "{{ obj|function:x }}";
</script>
This isn't possible, because the expression {{ obj|function:x }} is parsed by Django on the server before the javascript is run by the browser, so Django can't access the javascript variable x. You can verify this yourself by looking at the page's HTML response in your browser's network tab
-- you will see that any template expression enclosed in {{ }} is replaced by whatever value it resolves to.
If you need to use a javascript variable in Django, an alternative could be to send the variable's value to a Django view on your server and run the function there. Then you can do any computation involving that value on the server and return the appropriate response to the browser to be displayed.

Should Django forms be populated on client-side when used as popus

My question is best described by example.
Consider a table of students. When I click on a student, a pop-up should be opened with comprehensive info on the student. At first, each time the user clicks on a student, I did a GET-request via Ajax, and populated the pop-up with the fetched response. In other words, I did something like this:
def my_view(request):
if request.method == 'GET':
model_instance = MyModel.objects.get(id = request.POST['id']):
context = {'my_form': MyForm(instance = model_instance)}
msg = render_to_string('my_template.html', context, request = request)
return JsonResponse({'object': msg}, safe = False)
else:
# POST-request for saving input data to db
And then in the JS code:
$.get(....., function(response){
$(response.object).modal('show');
}
The problem with this code is that the pop-up appears with a delay. Well, yes, it's half a second, and yet I would like the response to be instant. Especially, if the user has slow internet, user experience is even worse.
What is the best-practice here ? On alternative that occurs to me is the following: when rendering the main page (with student tables), pass an empty form (or as Django doc calls it, unbound form by doing my_form = MyForm()), and then populate it with JavaScript when the user clicks on a student. Well, this approach yields super-fast pop-up rendering, and yet the approach is not DRY, the case with ForeignKey fields is very nasty here, and in general, this approach seems junk code
Populating the form with JavaScript doesn't have to be ugly. I've done something like this before using HTML data- attributes to help keep things clean. If you're using jQuery, it could look something like this:
{% for student in students %}
<div class="student" data-student-id="{{ student.id }}" data-student-first-name="{{ student.first_name }}">
{{ student.first_name }}
</div>
{% endfor %}
<!-- Pretend this is inside a modal -->
{{ form.as_p }}
<script>
$('.student').click(function() {
var studentId = $(this).data('student-id');
var firstName = $(this).data('student-first-name');
$('#id_id').value = studentId;
$('#id_first_name').value = firstName;
});
</script>
This assumes that Student.id is a HiddenInput Widget.
It doesn't take much JS to get you a pretty good result.

Best way to share data between node.js and django?

I have a variable in django settings.(eg settings.ALLOW_REDIRECT). I am running some tests (django and node.js tests) and the value of settings.ALLOW_REDIRECT would be changed after some tests.
What is the best way to let the node.js tests to access the value of the variable. I thought of using a conf file in which the value of variable can be stored and altered by django. This can be read by the node.js script. Is there any simpler method than this?
You can pass the value of settings.ALLOW_REDIRECT into your template render call:
def myview(request):
...
return render(request, 'mytemplate.html', {'allow_redirect': settings.ALLOW_REDIRECT})
And then the template can check the value of allow_redirect and insert some small unique element into the page HTML to reflect its value:
{% if allow_redirect %}
<div id="allow_redirect_is_true"> </div>
{% else %}
<div id="allow_redirect_is_false"> </div>
{% endif %}
And then your js code can check for the presence of an element with an id of allow_redirect_is_true or allow_redirect_is_false.

List.pop() in Django Template without for loop

I have a list of id all_entries_user. They basically serve as a part of url for rest service that I have developed using TastyPie. Inside my Django template i want to use them by iterating all_entries_user
function ajaxCall(){
$.getJSON("http://localhost:8000/api/Location/" + {{ all_entries_user.pop }} + "/?format=json",
function(json) {
convert(json,"googleMapUser");
}
);
}
Using this I am getting values from Service and this happens in a continous interval .
interval = startInterval(ajaxCall, 3000);
The value of url must change for each call and it must be taken from list
all_entries_user
gives me the same id every time.
I tried to pop values but each time gives me same value
I havent found an efficient way to iterate through this.
Suggestions and Help Please
Why don't you use the for construct?
{% for user in all_entries_user %}
Do your thing with {{ user }}
{% endfor %}
It's very confusing when you mix two languages. What's happening is your javascript is getting "Built" once when the template is rendered so you only have one URL regardless of how many times javascript hits that method. You can verify this by using view source and checking out what your javascript looks like to the client.
If you want the client to call a different URL each time, you will have to send all the IDs down to the client first. One way to do this is by using json serializer or just a simple home grown javascript array builder.
Something like this might work:
<script>
var allEntries = [{% for entry in all_entries_user %}{{ entry.id }},{% endfor %}];
for (entryId in allEntries) {
doSomethingWith(entryId);
}
</script>
This isn't the best way to populate an array of javascript from django, but it works in a hurry.

Insert JavaScript variable in Django tag

I'm working on an app that uses Django and jQuery for various things. I'm trying to assemble an AJAX request with jQuery that requires that I use Django's {% url %} template function. One of the arguments needed for the url call is stored in a JavaScript variable. Is it possible to insert the value of the JS var into the {% url %} tag? Something like
var jsvar = somestuff;
{% url some.view arg1=jsvar %}
No. Pass a sentinel (e.g. %s) to url which you replace in JavaScript with the actual value.

Categories