iT邦幫忙

2025 iThome 鐵人賽

DAY 5
0
AI & Data

打造你的數位圖書館:從雜亂檔案到個人化知識庫系列 第 5

DAY5 - 題目詳情&切換答案顯示

  • 分享至 

  • xImage
  •  

今天稍微優化一些前端,再加上題目詳情(來源檔案、書籍)和切換答案顯示的功能。

▍程式碼

  1. 修改views.py,加入題目詳情需要的資訊
<h5>搜尋結果</h5>
↓
<h5>{{ result_word }}</h5>
# views.py

def search():
    ...
    if query:
        # 把原先的"搜尋結果"字樣改為搜尋後才出現,沒有查到的話則出現"查無結果"
        result_word = "查詢結果"
        for item in KNOWLEDGE_BASE:
            if (...):
                search_results.append({
                    ...
                    "book_source": item.get("來源書籍", ""),
                    "page_number": item.get("頁次", ""),
                    "source_filename": item.get("來源檔案", ""),
                    "answer": item.get("答案", "")
                })
        if search_results == []:
            result_word = "查無結果"
    else: ...

    return render_template(
        ...
        result_word=result_word,
        # 來源檔案路徑
        source_path=os.path.join( "來源資料夾路徑" )
    )
  1. 加上顯示答案按鈕、題目詳情,修改if判斷式
<!-- index.html -->

<!-- 搜尋結果區域 -->
<div>
    <div>
        <div>
            <h5>{{ result_word }}</h5>
            {% if results %}
            <button id="toggle-answer">顯示答案</button>
        </div>

        <div id="search-results">
            ...
                <!-- 加入題目詳情區塊 -->
                <div class="question-info">
                    {% for source in result.source_filename %}
                    <a href={{ source_path }}/{{ source }}
                        target="_blank">{{ source }}
                    </a>
                    {% endfor %}
                    &nbsp;{{ result.book_source }}
                    &nbsp;p.{{ result.page_number }}
                </div>
                <ul>
                    {% set labels = ['A', 'B', 'C', 'D'] %}
                    {% for option in result.options %}
                    <!-- 如果這個選項是答案,就加上 class="answer" 屬性 -->
                    {% if option == result.answer %}
                    <li class="answer">({{ labels[loop.index0] }}) {{ option }}</li>
                    {% else %}
                    <li>({{ labels[loop.index0] }}) {{ option }}</li>
                    {% endif %}
                    {% endfor %}
                </ul>
            </div>
            {% endfor %}
            {% endif %}
        </div>
    </div>
</div>
  1. 偵測按鈕,切換按鈕文字,並將答案切換成 class="answer_highlight" 屬性
.answer_highlight {
    color: var(--bs-blue);
    font-weight: bold;
}
<!-- jquery cdn -->
<script>
    $(document).ready(function () {
        $('#toggle-answer').on('click', function () {
            $('.answer').toggleClass('answer_highlight');

            if ($(this).text() === "顯示答案") {
                $(this).text("隱藏答案");
            } else {
                $(this).text("顯示答案");
            }
        });
    });
</script>

上一篇
DAY4 - 去除重複題目
系列文
打造你的數位圖書館:從雜亂檔案到個人化知識庫5
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言