Django重用javascript代码的最佳实践

时间:2015-10-01 17:24:17

标签: javascript jquery python django templates

我有两个外部库(jQuery X-editable和FineUploader)所需的javascript代码,我需要我的上下文变量。因此,我不能使用外部js代码。

这就是我目前在模板上所做的事情:

some_important_template.html

GetData()

fine_upload_template.html

{% include "includes/editable_fields.html" %}
{% include "includes/fine_upload_template.html" %}

editable_fields.html

<script type="text/template" id="qq-template">

    <div class="qq-uploader-selector qq-uploader" qq-drop-area-text="Drop files here">
        <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
            <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
        </div>
        <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
            <span class="qq-upload-drop-area-text-selector"></span>
        </div>
        <div class="qq-upload-button-selector btn btn-info">

            <div>Upload a file</div>
        </div>
        <span class="qq-drop-processing-selector qq-drop-processing">
            <span>Processing dropped files...</span>
            <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
        </span>
        <ul class="qq-upload-list-selector qq-upload-list" aria-live="polite" aria-relevant="additions removals">
            <li>
                <div class="qq-progress-bar-container-selector">
                    <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>
                </div>
                <span class="qq-upload-spinner-selector qq-upload-spinner"></span>
                <img class="qq-thumbnail-selector" qq-max-size="100" qq-server-scale>
                <span class="qq-upload-file-selector qq-upload-file"></span>
                <span class="qq-edit-filename-icon-selector qq-edit-filename-icon" aria-label="Edit filename"></span>
                <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
                <span class="qq-upload-size-selector qq-upload-size"></span>
                <button type="button" class="qq-btn qq-upload-cancel-selector btn btn-danger">Cancel</button>
                <button type="button" class="qq-btn qq-upload-retry-selector btn btn-info">Retry</button>
                <button type="button" class="qq-btn qq-upload-delete-selector qq-upload-delete">Delete</button>
                <span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>
            </li>
        </ul>

        <dialog class="qq-alert-dialog-selector">
            <div class="qq-dialog-message-selector"></div>
            <div class="qq-dialog-buttons">
                <button type="button" class="qq-cancel-button-selector">Close</button>
            </div>
        </dialog>

        <dialog class="qq-confirm-dialog-selector">
            <div class="qq-dialog-message-selector"></div>
            <div class="qq-dialog-buttons">
                <button type="button" class="qq-cancel-button-selector">No</button>
                <button type="button" class="qq-ok-button-selector">Yes</button>
            </div>
        </dialog>

        <dialog class="qq-prompt-dialog-selector">
            <div class="qq-dialog-message-selector"></div>
            <input type="text">
            <div class="qq-dialog-buttons">
                <button type="button" class="qq-cancel-button-selector btn btn-danger">Cancel</button>
                <button type="button" class="qq-ok-button-selector btn btn-info">Ok</button>
            </div>
        </dialog>
    </div>

</script>

<script>

    var uploader = new qq.FineUploader({
        debug: true,
        element: document.getElementById('fine-uploader'),
        request: {
            endpoint: '{% url "registrations:ajax_upload" registration.pk %}',
            params: {
                'csrfmiddlewaretoken': '{{ csrf_token }}'
            }
        },
        deleteFile: {
            enabled: false,
            endpoint: '/uploads'
        },
        retry: {
           enableAuto: false
        }
    });

</script>

这有效,但我不确定它是否遵循Django Best Practices。

1 个答案:

答案 0 :(得分:3)

组合javascript和Django模板代码并不是一个好主意。

相反,在你的javascript周围编写一个包装函数来获取所有模板变量。即创建一个包含以下内容的javascript文件:

var wrapper = function (args) {
    //turn to inline mode
    $.fn.editable.defaults.mode = 'inline';

    if (args.registration_emergency_contact) {

        $('#contact_first_name').editable({
            name: 'first_name',
            pk: args.registration_emergency_contact_id,
            url: args.profiles_field_inline,
            params: "{csrfmiddlewaretoken:'" + args.csrf_token + "', model: 'User'}"
        });
     // ...
}
在您的视图中,将args创建为json值:

def myview(...):
    args = {
         'registration_emergency_contact': bool(registration.emergency_contact),
         'registration_emergency_contact_id': registration.emergency_contact.id,
         'profiles_field_inline': reverse(...),
         // ...
    }
    return ... , Context({'args': json.dumps(args)})..

然后在您的模板文件中,通过脚本标记包含javascript文件并调用函数:

wrapper({{ args|safe }});

这样你的javascript只包含javascript,你可以使用所有可用的javascript工具来lint / minifiy / transpile /等,并将其作为静态资源提供。