Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django variables to javascript

I'm trying to make a gallery page using django/js/jquery. Is it possible to pass django template variables to the javascript? I need to implement for loop like:

{% for post in object_list %}
    {% post.title %}
    {% post.url %}
{% endfor %}

In my base template I just add my script: (base.html)

<script src="{{STATIC_URL}}assets/js/script.js"></script>

(function($){
    var photos = [
        'media/photos/1.jpg',
        'media/photos/2.jpg', // I need to get them through a for loop
        'media/photos/3.jpg',
        'media/photos/4.jpg',
    ];
    $(document).ready(function(){
        var page = 0,
            loaded = 0,
            perpage = 5,
            main = $('#main'),
            expected = perpage,
            loadMore = $('#loadMore');
        main.on('image-loaded', function(){
            loaded++;
            NProgress.set(loaded/expected);

            if(page*perpage >= photos.length){
                loadMore.remove();
            }
        });
        loadMore.click(function(e){
            e.preventDefault();
            loaded = 0;
            expected = 0;
            var deferred = $.Deferred().resolve();
            $.each(photos.slice(page*perpage, page*perpage + perpage), function(){
                deferred = main.showImage(this, deferred);
                expected++;
            });
            NProgress.start();
            page++;
        });
        loadMore.click();
    });
    $.fn.showImage = function(src, deferred){
        var elem = $(this);
        console.log(elem);
        var result = $.Deferred();
        var holder = $('<div class="photo" />').appendTo(elem);
        var datetime = $('<p>test</p>').appendTo(elem); // and add {{ post.date }} here
        var img = $('<img>');
        img.load(function(){
            deferred.always(function(){
                elem.trigger('image-loaded');
                img.hide().appendTo(holder).delay(100).fadeIn('fast', function(){

                    result.resolve()
                });
            });
        });

        img.attr('src', src);
        return result;
    }
})(jQuery);
like image 225
stk-13 Avatar asked Nov 26 '13 18:11

stk-13


1 Answers

If you are including js file as:

<script type="text/javascript" src="{% static 'js/some_file.js' %}"></script>

Then you cannot access request context in some_file.js. What you can do is that either move the js code in the template or move it to child template (for reusability) to access request context and include it as:

{% include "some_template_including_js_code.html" %}

Then in the js code you can iterate over context variable containing images url:

<script type="text/javascript">
    var photos = [];
    {% for image in images %}
        photos.push('{{ image }}');
    {% endfor %}
</script>
like image 109
Aamir Rind Avatar answered Nov 02 '22 23:11

Aamir Rind