【负载均衡式在线OJ项目day8】View模块实现——网页渲染

一.前言

这里的网页渲染指的是,将一个模版html中以双花括号({{}})括起来的变量,替换成相应的数据值,以实现内容动态展示。

网页渲染模块和数据交互模块搭配使用,就能给用户展示各种各样的网页

二.设计思路

我们使用的是第三方库ctemplate,这个库需要编译源代码安装,首先需要在gitee或者github找到源代码下载下来,然后使用提供的编译脚本进行编译,最后用提供的安装脚本进行安装建议找一篇文章看看。

注意:gcc版本必须是7及以上;使用超级用户权限安装

我们只需渲染两个html模版:题目列表和指定题目,因此只需对外提供两个方法。传进来题目的信息,把渲染后的html以字符串的形式返回给外部。

三.代码实现

 OjView.hpp:

#pragma once
#include <vector>
#include <string>
#include <ctemplate/template.h>
#include "OjModel.hpp"
namespace ns_oj_view
{
    const std::string templateHtmlPath = "./template_html/";
    using namespace ns_oj_model;
    class OjView
    {
    public:
        /******************************
         * 功能:用questions渲染网页模版,得到题目列表的网页
         * ***************************/
        void questionListExpandHtml(const std::vector<Question> &questions, std::string *html)
        {
            const std::string pathName = templateHtmlPath + "question_list.html";

            //形成数据字典
            ctemplate::TemplateDictionary root("questionList");
            for (auto &q : questions)
            {
                ctemplate::TemplateDictionary *sub = root.AddSectionDictionary("questionLine");
        
                // 题目编号 标题 难度
                sub->SetValue("number", q._number); //左边是key,右边时value
                sub->SetValue("title", q._title);
                sub->SetValue("star", q._star);
            }

            //获取待渲染的html模版,并且不要删除其中的空行
            ctemplate::Template* tpl = ctemplate::Template::GetTemplate(pathName, ctemplate::DO_NOT_STRIP);

            tpl->Expand(html, &root); //用数据字典root渲染tpl,结果放到html中
        }

        /******************************
         * 功能:用q渲染网页模版,得到指定题目编写的网页
         * ***************************/
        void oneQuestionExpandHtml(const Question &q, std::string *html)
        {
            const std::string pathName = templateHtmlPath + "one_question.html";

            ctemplate::TemplateDictionary root("oneQuestion");
            root.SetValue("number", q._number);
            root.SetValue("title", q._title);
            root.SetValue("star", q._star);
            root.SetValue("pre_code", q._header);
            root.SetValue("desc", q._desc);

            ctemplate::Template* tpl = ctemplate::Template::GetTemplate(pathName, ctemplate::DO_NOT_STRIP);
            
            tpl->Expand(html, &root);
        }
    };
}

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值