Python Web开发:向模板传递动态参数

来自CloudWiki
跳转至: 导航搜索

背景

访问页面 http://127.0.0.1:8000/

单击首页上“科研基地”链接,

跳转到 http://127.0.0.1:8000/scienceApp/science/

会发现导航栏的激活效果没有同步切换。

这需要在页面渲染的过程中根据实际情况进行导航栏激活状态转换。

实训步骤

为导航链接标签<li>设置id号

base.html:

<li class="nav-top" id='science'>
                        <a href="{% url 'scienceApp:science' %}">科研基地</a>
                    </li>

设置JS动态添加active属性

base.html:

    <script type="text/JavaScript">
        $('#{{active_menu}}').addClass("active");
    </script>

向模板传递active_menu变量

scienceApp/views.py:

from django.shortcuts import render
from django.shortcuts import HttpResponse


# Create your views here.
def science(request):    
    return render(request,'science.html',{'active_menu':'science',})

效果图

Python21050101.png