创建一个循环来打印 html 列表

发布于 2024-12-06 09:04:07 字数 2444 浏览 1 评论 0原文

我需要创建一个类似于以下形式的 html 列表:

<ul class="treeView">
    <li>
        Root Item
        <ul class="collapsibleList">
        <li>
            Sub-Folder 1
            <ul>
                <li>
                    Sub-Sub-Folder 1
                    <ul>
                        <li>Item 1</li>
                        <li class="lastChild">Item 2</li>
                    </ul>
                </li>
                <li class="lastChild">
                    Sub-Sub-Folder 2
                    <ul>
                        <li>Item 3</li>
                        <li class="lastChild">Item 4</li>
                    </ul>
                </li>
            </ul>
        </li>
            <li class="lastChild">
                Sub-Folder 2
                <ul>
                    <li>Item 5</li>
                    <li>Item 6</li>
                    <li class="lastChild">Item 7</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

该列表基于目录结构,但我有用于列出实际结构的代码。所以我需要的是如何使用 for 循环来跟踪所有内容并创建嵌套的 html 列表。

下面是我到目前为止所拥有的 python 脚本:

for item in lstItems:
    splitfile = os.path.split(item[0])
    webpyPath = splitfile[0].replace("/srv/http/example/www", "")
    itemName = splitfile[1]
    if item[1] == 0:
        lstRemDir.append(itemName)
    intDirNum = len(lstRemDir) - 1
    if item[1] == 0:
        if len(lstRemDir) == 1:
            print '''
<ul class="treeView">
    <li>Collapsible lists
        <ul class="collapsibleList">
            '''
        elif len(lstRemDir) != 1:
            f.write('    </ul>\n</li>')
        f.write('<li><a href=\"' + webpyPath + "/" + itemName + '\" id=\"directory\" alt=\"' + itemName + '\" target=\"viewer\">' + itemName + '</a></li>\n')
    elif item[1] == 1:
        f.write('<li><a href=\"' + webpyPath + "/" + itemName + '\" id=\"file\" alt=\"' + itemName + '\" target=\"viewer\">' + itemName + '</a></li>\n')
    else:
        f.write('<li>An error happened in processing ' + itemName + '.')

我问这个问题的原因是因为我几天来一直在试图解决这个问题。我并不是要求别人为我做这件事,只是一个好方法。我尝试过使用列表来存储数据,但我觉得它太混乱了。希望这能澄清我在寻找什么。

提前致谢!

I need to create a html list similar in form to the following:

<ul class="treeView">
    <li>
        Root Item
        <ul class="collapsibleList">
        <li>
            Sub-Folder 1
            <ul>
                <li>
                    Sub-Sub-Folder 1
                    <ul>
                        <li>Item 1</li>
                        <li class="lastChild">Item 2</li>
                    </ul>
                </li>
                <li class="lastChild">
                    Sub-Sub-Folder 2
                    <ul>
                        <li>Item 3</li>
                        <li class="lastChild">Item 4</li>
                    </ul>
                </li>
            </ul>
        </li>
            <li class="lastChild">
                Sub-Folder 2
                <ul>
                    <li>Item 5</li>
                    <li>Item 6</li>
                    <li class="lastChild">Item 7</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

This list is based off a directory structure, but I have the code down for listing the actual structure. So all I need is how to use the for loop to keep track of everything and create the nested html lists.

Below is my python script that I have so far:

for item in lstItems:
    splitfile = os.path.split(item[0])
    webpyPath = splitfile[0].replace("/srv/http/example/www", "")
    itemName = splitfile[1]
    if item[1] == 0:
        lstRemDir.append(itemName)
    intDirNum = len(lstRemDir) - 1
    if item[1] == 0:
        if len(lstRemDir) == 1:
            print '''
<ul class="treeView">
    <li>Collapsible lists
        <ul class="collapsibleList">
            '''
        elif len(lstRemDir) != 1:
            f.write('    </ul>\n</li>')
        f.write('<li><a href=\"' + webpyPath + "/" + itemName + '\" id=\"directory\" alt=\"' + itemName + '\" target=\"viewer\">' + itemName + '</a></li>\n')
    elif item[1] == 1:
        f.write('<li><a href=\"' + webpyPath + "/" + itemName + '\" id=\"file\" alt=\"' + itemName + '\" target=\"viewer\">' + itemName + '</a></li>\n')
    else:
        f.write('<li>An error happened in processing ' + itemName + '.')

The reason I am asking is because I have been trying to get this figured out for days. I am not asking for someone to do it for me, just a good way to do it. I have tried using lists to store data but I felt like it got too confusing. Hopefully that clarifies what I am looking for.

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见你 2024-12-13 09:04:07

这可能有助于您开始使用一种更简单的解决方案,该解决方案使用嵌套字典来表示您的文件而不是列表:

dir = {}
start = rootdir.rfind('/')+1
for path, dirs, files in os.walk(rootdir):
    folders = path[start:].split('/')
    subdir = dict.fromkeys(files)
    parent = reduce(dict.get, folders[:-1], dir)
    parent[folders[-1]] = subdir

下面是一个示例,说明 dir 的结构与您的文件中的结构类似。示例:

{
    "root": {
        "folder2": {
            "item2": None, 
            "item3": None, 
            "item1": None
        }, 
        "folder1": {
            "subfolder1": {
                "item2": None, 
                "item1": None
            }, 
            "subfolder2": {
                "item3": None, 
                "item4": None
            }
        }
    }
}

使用这个,编写一个接受字典并返回 html 列表的递归函数应该不会太困难。这是一个简单的函数,仅以正确的级别打印项目,您应该能够修改它以添加 html 代码:

def html_list(nested_dict, indent=0):
    result = ''
    if nested_dict is not None:
        for item in sorted(nested_dict.keys()):
            result += ' '*indent + item + '\n'
            result += html_list(nested_dict[item], indent+4)
    return result

>>> print html_list(dir)
root
    folder1
        subfolder1
            item1
            item2
        subfolder2
            item3
            item4
    folder2
        item1
        item2
        item3

This might help to get you started on a simpler solution that uses a nested dictionary to represent your files instead of lists:

dir = {}
start = rootdir.rfind('/')+1
for path, dirs, files in os.walk(rootdir):
    folders = path[start:].split('/')
    subdir = dict.fromkeys(files)
    parent = reduce(dict.get, folders[:-1], dir)
    parent[folders[-1]] = subdir

Here is an example of what dir might look like for a similar structure to the one in your example:

{
    "root": {
        "folder2": {
            "item2": None, 
            "item3": None, 
            "item1": None
        }, 
        "folder1": {
            "subfolder1": {
                "item2": None, 
                "item1": None
            }, 
            "subfolder2": {
                "item3": None, 
                "item4": None
            }
        }
    }
}

Using this it shouldn't be too difficult to write a recursive function that accepts a dictionary and returns an html list. Here is a simple function that just prints the items out at the correct level, you should be able to modify this to add the html code:

def html_list(nested_dict, indent=0):
    result = ''
    if nested_dict is not None:
        for item in sorted(nested_dict.keys()):
            result += ' '*indent + item + '\n'
            result += html_list(nested_dict[item], indent+4)
    return result

>>> print html_list(dir)
root
    folder1
        subfolder1
            item1
            item2
        subfolder2
            item3
            item4
    folder2
        item1
        item2
        item3
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文