Skip to content
Snippets Groups Projects
Commit f313b54c authored by Axel Dürkop's avatar Axel Dürkop
Browse files

Upload New File

parent 9bcdfeb3
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# Dynamisches Generieren einer Navigation mit Python
%% Cell type:code id: tags:
``` python
navi = ["Home", "Kontakt", "Impressum"]
nav_wrapper = '<nav><ul style="list-style: none;">{}</ul></nav>'
nav_item_wrapper = '<li><a href="#">{}</a></li>'
nav_items = ""
for n in navi:
nav_items = nav_items + nav_item_wrapper.format(n)
html_navigation = nav_wrapper.format(nav_items)
print(html_navigation)
```
%% Output
<nav><ul style="list-style: none;"><li><a href="#">Home</a></li><li><a href="#">Kontakt</a></li><li><a href="#">Impressum</a></li></ul></nav>
%% Cell type:markdown id: tags:
## Ein Trick für's Notebook
%% Cell type:markdown id: tags:
Um das generierte HTML aus "als" HTML ausgeben zu können, müssen wir uns hier im Notebook eines Trick bedienen.
%% Cell type:code id: tags:
``` python
from IPython.display import HTML
HTML(html_navigation)
```
%% Output
<IPython.core.display.HTML object>
%% Cell type:markdown id: tags:
## Keine Liste, sondern Dicationary
%% Cell type:markdown id: tags:
Statt einer Liste verwenden wir nun ein *dictionary*:
%% Cell type:code id: tags:
``` python
navi = {
"home" : {
"name": "Home",
"url": "http://heise.de",
"external": True
},
"kontakt": {
"name": "Kontakt",
"url": "http://spiegel.de",
"external": False
}
}
print(navi["kontakt"]["url"])
```
%% Output
http://spiegel.de
%% Cell type:code id: tags:
``` python
nav_wrapper = '<nav><ul style="list-style: none;">{}</ul></nav>'
nav_item_wrapper = '<li><a href="{}">{}</a></li>'
nav_items = ""
for key, value in navi.items():
nav_items = nav_items + nav_item_wrapper.format(value["url"],value['name'])
html_navigation = nav_wrapper.format(nav_items)
print(html_navigation)
```
%% Output
<nav><ul style="list-style: none;"><li><a href="http://spiegel.de">Kontakt</a></li><li><a href="http://heise.de">Home</a></li></ul></nav>
%% Cell type:code id: tags:
``` python
from IPython.display import HTML
HTML(html_navigation)
```
%% Output
<IPython.core.display.HTML object>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment