简体   繁体   中英

Issue with custom template tags in Django?

I think my template tags are being called when I don't want them to be called, but I can't find a fix anywhere. This is what I have in html:

{% load cTemplateTags %}
    {% if n.priority == 1 %}
        {% if not n.read %}

        <li>
            <div class="alert alert-dismissible alert-warning">
                <button type="button" class="close" data-dismiss="alert" onclick="{% set n = True %}">x</button>
                <a href="{{n.url}}" class="alert-link"> {{n.message}}</a>
            </div>
        </li>
        {% endif %}

    {% endif %}

In my template tags:

from django import template
from notifications.models import Notification
register = template.Library()


class SetVarNode(template.Node):

    def __init__(self, var_name, var_value):
        self.var_name = var_name
        self.var_value = var_value

    def render(self, context):
        try:
            value = template.Variable(self.var_value).resolve(context)
        except template.VariableDoesNotExist:
            value = ""


        for n in Notification.objects.all():
            if n.actor == context[self.var_name].actor:
                if n.message == context[self.var_name].message:
                    if n.priority == context[self.var_name].priority:
                        if n.date == context[self.var_name].date:
                            n.read = bool(self.var_value)
                            n.save()


        return u""


@register.tag(name='set')
def set_var(parser, token):
    """
    {% set some_var = '123' %}
    """

    parts = token.split_contents()
    if len(parts) < 4:
        raise template.TemplateSyntaxError("'set' tag must be of the form: {% set <var_name> = <var_value> %}")

    print(token)
    #print(parts[3])
    return SetVarNode(parts[1], parts[3])

Is there anyway to get my onClick in the HTML to only fire when the button is actually clicked? For whatever reason when I reload the page the value is set to True even though I never clicked the button. Please let me know if you guys can think of anything!

Templates are rendered by the server. Which means all the tags get processed on the server and a plain HTML page is then generated which is sent to the browser/client.

In short:

<button onClick="{% set n = True %}">x</button>

will be rendered to the browser/client as:

<button onClick="True">x</button>

UPDATE

Since, you're trying to update the value of n.read asynchronously when a button is clicked, you'll need to find a way to communicate to the server to update the value of n.read .

Below is a minimal example of performing an AJAX request to the server using jQuery library.

<button id="myBtn" data-id="{{ n.id }}">x</button>

<!-- JavaScript -->
<!-- Don't forget to include jQuery -->
<script>
$("#myBtn").on('click', function(), {
    var nId = $(this).attr('data-id');
    $.ajax({
        type: 'POST',
        url: '/link/to/the/view/',
        data: {'id': nId}, // this way server will know which object to update
    });
});
</script>

Now, an AJAX request will be made to the server. You'll need to implement a view on the server which takes care of updating and saving the n object.


UPDATE 2

You can find a lot more examples on using Django and AJAX (jQuery) by searching StackOverflow. Well, you can start here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM