I am new to OctoberCMS so I don't know a lot of things.
I read the October documentation and i know how to pass variables when using partials in the static way:
{% partial "location" city="Vancouver" country="Canada" %}
My problem is that I need to use php or js variables. Let's say I have an input field where the user writes an ID, then after a button is pressed I want to pass the ID to a partial. I am trying to do something like this :
{% partial "location" city=$city country=$country %}
Can someone help me? Thank you.
Have you tried this method as documented here? https://octobercms.com/docs/cms/partials#partial-variables
{% partial "location" city=city country=country %}
EDIT
As an aside, you need to define your page variables in the onStart function.
url = "/blah"
layout = "default"
==
<?
function onStart()
{
$this['country'] = ...;
$this['city'] = ...;
}
?>
==
{% partial "location" city=city country=country %}
EDIT
Have you read the section on AJAX? https://octobercms.com/docs/ajax/introduction
More specifically - https://octobercms.com/docs/ajax/update-partials#pushing-updates AND https://octobercms.com/docs/ajax/update-partials#update-definition
EDIT
Just re-read your original question and you're asking about binding to form elements, not AJAX.
Take a look at the JS API - https://octobercms.com/docs/ajax/javascript-api#javascript-api
I think you could do something like:
<form onsubmit="$(this).request('onMyProcessingMethod'); return false;">
$('form').request('onMyProcessingMethod', {
update: {myPartialName: '.whereIWantTheOutputToGo'},
data: {country: 'Canada'} // Not 100% sure how to access form input; maybe ID selector
})
You can use variables inside the partial in this way:
<p>Country: {{ country }}, city: {{ city }}.</p>
Related
I am using Flask and wtforms to create a web page "index.html" that loads multiple forms. The selection of forms that are rendered depend on dropdown selections, and a variable "serviceid" updated from an API call. The form selection and rendering is handled in an included file "form_select.html", which requires "serviceid" value to pick the correct form. I am having trouble figuring out how to refresh the forms based on updated serviceid values without doing a full page reload.
I can use something like this with jinja2 include to render "form_select.html" and pass the "serviceid" variable so the right form is rendered:
<div id="loadform"> {% include './form_select.html' with serviceid %} </div>
This is working on first load, but I need to select a new form when the user selects a new value from a dropdown. I am running a script based on mydropdown.onchange, which first obtains the correct "serviceid" value, but now I need to rerender just the loadform div with this value.
I have tried approaches along the lines of the following - but I cant seem to figure out how to deliver this jinja2 with .innerHTML.
document.getElementById('loadform').innerHTML = `
{% with serviceid=serviceid %}
{% include './form_blocks.html' %}
{% endwith %}
`;
There is probably a better way to do this, but the examples I can find don't include passing in a variable. Can I use innerHTML for this, or is there a better way?
In Django, I have a variable flag=True.
I pass it to script in Html :
<script>
if({{flag}}==True) do something
</script>
I assume do something will be called, but it is not. It looks like True not equal to True. Could anyone teach me how to fix it?
You should do like this
<script>
{% if flag %}
do something
{% endif %}
</script>
You are trying to check the javascript condition with python boolean value. The above example is in django template engine. But still you want to check the condition in javascript, you have to do like this.
<script>
if ({{flag}}) {
do something
}
</script>
The problem is due to the ajax implementation in my django twitter clone app, the like count for every post is showing the same after clicking the like button.but after the page refresh that is okay. I am near to solve the problem but stuck somehow.
view:
def add_like(request):
if request.method == 'GET':
ans_id = request.GET['id']
user = request.user.profile
liked_tweet = get_object_or_404(Tweet, pk=ans_id)
if ans_id:
# creating instance by sending the Like table fields
instance, created = Like.objects.get_or_create(liker=user, liked_tweet=liked_tweet)
ans = Tweet.objects.get(id=(int(ans_id)))
if ans:
likes = ans.likes + 1
ans.likes = likes
ans.save()
# returns the likes field of a tweet post
return HttpResponse(likes)
the HttpResponse is sending the likes and that creates the problem I guess.
the template:
{% for tw in tweets %}
<div class="blog-post">
<p>
{{ tw.content|safe }}<br><hr>
<small class="small">
লিখসে -
<!-- in the "href" we can pass data like "pk", accessing by the structure the current object is based on-->
{{ tw.tweeter.user.username|capfirst }}
</small>
</p>
{% if user.is_authenticated %}
<button class="btn btn-default likes-button" type="button"
data-ansid="{{ tw.pk }}">Like</button>
<i> Total Likes: </i><em class="like_count">{{ tw.likes }}</em>
{% endif %}
</div>
the ajax script:
$(".likes-button").click(function(e) {
if ($(this).html() == "Like") {
$(this).html('Unlike');
//alert("js working");
// error was there for "data" insted of "attr"
var ansid = $(this).attr("data-ansid");
$.ajax({
url: '{% url "add_like" %}',
type: 'get',
data: {id: ansid}
}).done(function (data) {
alert("success");
$('.like_count').html(data);
//$('#likes').hide();
}).fail(function (err) {
alert(err);
});
}
Thanks in advance.
I think the very first comment by Sayse gives your answer. I am just trying to give a bit more explanation.
So What you have done is after a successful ajax request, you replace existing like count with the data you get from ajax in any the element who have a class named .like_count.
Check In your code $('.like_count').html(data); This select all the elemnt having like_count class and change the html.
Instead, what you should've done is after a successful ajax, change the data only in one place. You need to choose appropriate jquery selector.
Something like .closest() can be used. In that case, use (following code is not tested) $(this).closest('.like_count').html(data); to apeend 'like count' in appropriate element.
Also you can assign dynamic ID to each 'like count' element based on id and then use exect ID Selector.
Hope this helps.
Cheers!
Did you say:
but after the page refresh that is okay
Since your code snippet works, you're simply looking for the likes count incrementation to happen and see the live update in the template.
Well, in theory, here:
The function that increments the like should return with a JSON response of the incremented value from the database.
A client function standing by accepts this JSON response, and updates the template value accordingly.
In Practicals:
See this answer: https://stackoverflow.com/a/31832275/1757321
I have a select box that calls a function on changes. The function finds the selected value from "Products" selectbox.
I want to throw that selected value to my views.py which after some operations return the list of data and Populates the Destination's selectbox.
I want to use ajax for this purpose. Please help.
My code looks like this:
<script type="text/javascript">
function select_value()
{
var e = document.getElementById("Product");
var prod = e.options[e.selectedIndex].text
console.log(prod)
}
</script>
This is what my selectbox look like:
<table>
<tr>
<td>
<select id="Product" onChange="select_value();">
{% for products in product_name_list %}
<option>{{products|safe}}</option>
{% endfor %}
</select>
</td>
<td>
<select id="dest">
{% for des in destinations_name_list %}
<option>{{des|safe}}</option>
{% endfor %}
</select>
</td>
</tr>
</table>
This is my views.py:
def selection_filter(request,prod):
destination_objs = Destination.objects.filter(product=prod)
destination_name = destination_objs.values_list('name')
destination_name_list = []
for iter_name in destination_name:
destination_name_list.append(iter_name[0].encode('utf-8'))
return render_to_response('temp/test.html',
{"destination_name_list" : destination_name_list},
)
I think the point you might be misunderstanding is that your Django template for your whole page will not be re-rendered "magically". In Django's standard model-view-template paradigm, the template is rendered just once, upon the initial request. The way you've written it, unless there's a default product selection, you're going to have an awkward empty <select> in the first render. But ignoring that...
For a problem like this, you need two views: one for rendering the whole page, and one for providing the Ajax response. There are two main options for the second view: 1) return JSON for interpretation/rendering by your script post-response or 2) return a fully rendered HTML fragment for direct insertion into your DOM. In this case, I'd just go for option 2.
I recommend looking into Jquery, as it makes Ajax and DOM manipulation super simple.
If you've got Jquery, it's as simple as adding to your script:
$.get('/destinations/' + prod)
.done(function (html) {
$(#dest).html(html);
});
(You can do the same thing without Jquery too, but it requires a bit more wrangling)
Your test.html file should contain:
{% for des in destinations_name_list %}
<option>{{des|safe}}</option>
{% endfor %}
I know that it is dumb question to ask but I need to know can I get form widget attributes through PHP I mean not a value but id, class or even parent or child. If I set them.
<label name = '{{ item.modulePath }}' id = 'main' class = 'menu_label' **parent = ''** **childs = ''**>{{ item.modulePath }}</label>
If it is not possible then how can I make JS function before form validation and post array to the form as value?
<form action="{{ path('menu_manage') }}" method="post">
Yes I could get values and submit form to JS and then by JS get all attributes and then through ajax send it to a PHP handler. But it would be longer, because I will need to include all components that have this action to the handle information to place where I need it.
Here is an example how to realize it
http://symfony2forum.org/threads/5-Using-Symfony2-jQuery-and-Ajax
You can call get() method on form field in template, e.g. having a form in form with field item:
{{ form.item.get('id') }}
The class - only if set - can be retrieved like this:
{{ form.item.get('attr').class }}