簡體   English   中英

使用 django 變量在 HTML 文件的腳本標記 (JS) 中作為上下文傳遞

[英]Use django variables passed as context in script tag (JS) of HTML file

我被困在我的 django webapp 中使用<script>標簽來呈現 googlemaps api window。 在我看來,我這樣傳遞了我的數據:

def map_view(request):
    context = {
        'title': 'My Map',
        'machines': Machine.objects.all(),
    }

    return render(request, 'gui/map_view.html', context)

我只是想利用機器對象(字符串)中包含的一些參數來自動生成 map 上的標記,但無法弄清楚如何在 javascript 代碼中使用machines 嘗試了{{ }}{% %}

如果我理解正確,那么您正試圖將存儲在每台機器中的位置數據放入某種 JavaScript 集合中。

你現在這樣做的方式可能需要一個有點像這樣的模板

<script>
  var machines = [ // define list with machine positions
  {% for machine in machines %} // use django templates to interact with the passed context
    machine.position, // I don't know what your Machine class looks like, but you get the idea
  {% endfor %}
  ];
</script>

在此處閱讀有關模板語言的信息

我懷疑這不是實現這一目標的最佳方式。 也許嘗試在 python 中將列表生成為字符串,然后在上下文中傳遞它。

我還在學習,所以希望對您有所幫助,我有一個 django 項目,其中有一個顯示電影列表的網頁,這是 views.py 代碼:

def movies_list(request):
    movies = Movie.objects.all().order_by('pk')
    return render(request, 'movies/movies_list.html', {'movies':movies, 'title':'Movie List'})  

HTML 部分是這樣的:

{% extends 'base_layout.html' %}
{% block content %}
    <div class="container">
        <div class="row">
            {% for movie in movies %}
            <a href="{% url 'movie_detail' pk=movie.pk %}" >
                <div class="col cell"><img src="{{ movie.movie_poster.url }}"></div>
            </a>
            {% endfor %}

        </div>

    </div>
{% endblock %}  

所以我將兩個參數傳遞給 html 1 頁面標題,第二個電影 object,我可以使用它的字段。

我多年來使用的一個方便的技巧......在你看來:

from json import dumps

def map_view(request):
    context = {
        'title': 'My Map',
        'machines': dumps(Machine.objects.all()),
    }

    return render(request, 'gui/map_view.html', context)

然后在您的模板中,在 JavaScript 中:

<script>
var machines = {{ machines }}

console.log(machines)
</script>

祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM