# cpphtmlbuilder
**Repository Path**: captorking/cpphtmlbuilder
## Basic Information
- **Project Name**: cpphtmlbuilder
- **Description**: 仅头文件的 c++ html构建器
- **Primary Language**: C++
- **License**: MIT
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2026-02-03
- **Last Updated**: 2026-02-03
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# cppHtmlBuilder
#### 介绍
仅头文件的 c++ html构建器。
从[CppTinParser](https://github.com/Smart-Space/CppTinParser)中分离而来,单独维护。
#### 特性
- 自由指定html标签名称、参数、参数值
- 动态添加或修改标签参数-值、内容
- 动态添加、修改、删除子元素
- 随时生成html文本
- 可获取亲元素、所有子元素
> **注意**:内部操作中的所有元素实例均以指针形式存在。所有元素尽可能创建在堆上,每个元素销毁时会自动销毁下辖所有元素。
#### 使用
导入头文件:
```c++
#include "htmlbuilder.hpp"
```
示例:
```c++
int main() {
HtmlElement root = {"html"};
// 短元素用add_with()方法添加
root.add((new HtmlElement{"head"})->add_with(new HtmlElement{"title", "My Page"}));
HtmlElement* body = new HtmlElement{"body"};
root.add(body);
HtmlElement* div = new HtmlElement{"div"};
body->add(div);
div->configkws({{"id", "main"}, {"class", "container<>"}});
div->configcnt("&
content内容&");
cout << div->parent()->render() << endl;// 输出父元素此刻的html代码
div->add(new HtmlElement{"h1", "cpphtmlbuilder"});
// 添加列表
HtmlElement* ul = new HtmlElement{"ul"};
div->add(ul);
for (int i = 0; i < 10; i++) {
ul->add(new HtmlElement{"li", to_string(i)});
}
// 删除倒数第二个li
{
auto it = prev(ul->children().end(), 2);
auto element = *it;
ul->children().erase(it);
delete element;// 仍在堆上,需要手动释放
}
div->add(new HtmlElement{"", "content内容,只要标签名为空即可"});
auto result = root.render();
cout << result << endl;
}
```
### 说明
通过唯一类`HtmlElement`构建html框架。
```c++
HtmlElement()=default;
HtmlElement(std::string tag, std::string content="", bool onetag=false, bool pre=false){
// tag 标签
// content 内容
// onetag 是否为单标签
// pre 是否直接写入内容而不用转义
}
HtmlElement(std::string tag, std::string content, std::map
kws, bool onetag=false, bool pre=false){
// kws 参数名-值,...
}
```
### 类方法
#### render
```c++
std::string HtmlElement::render(std::string split_s="\n");
// split_s 间隔文本
```
将当前标签输出为字符串,例如:
```c++
HtmlElement html = HtmlElement{"html"};
html.add(new HtmlElement{"div"});
cout << html.render() << endl;
/*
*/
```
#### add
```c++
void HtmlElement::add(HtmlElement* item);
```
向本标签中添加子元素。
#### add_with
```c++
HtmlElement* HtmlElement::add_with(HtmlElement* item);
// return this
```
向本标签中添加子元素,并返回自身。用于链式添加,例如:
```c++
HtmlElement root = {"html"};
root.add((new HtmlElement{"head"})
->add_with(new HtmlElement{"title", "My Page"})
->add_with(new HtmlElement{"meta"})
->add_with(new HtmlElement{"meta"}));
cout << root.render() << endl;
/*
My Page
*/
```
#### configcnt
```c++
void HtmlElement::configcnt(std::string content);
```
设置标签内容。
#### configkws
```c++
void HtmlElement::configkws(std::map kws);
```
设置标签**全部参数**。
#### parent
```c++
HtmlElement* HtmlElement::parent();
```
获取亲元素,若没有返回空指针。
#### children
```c++
std::list& HtmlElement::children()
```
获取所有子元素,返回的是内部`list`的引用。