learning-website-framework1-2 Exercise 2: site_for() — Which Site Does This Page Belong To? ============================================================================================= Write a function that takes a content-relative path and returns the site name, including pages under sidebar// (routed by subject). SITES = { "languages": ["france", "germany", "hungary", "japan", "culture"], "webdevelopment": ["web-development", "web-platforms", "web-servers"], "systems": ["linux", "operating-systems"], "humanities": ["history"], } SIDEBAR_ROUTES = {"linux": "systems", "history": "humanities", "web-development": "webdevelopment"} FOLDER_TO_SITE = {f: s for s, fs in SITES.items() for f in fs} def site_for(path): parts = path.strip("/").split("/") if parts[0] == "sidebar": if len(parts) < 2: raise ValueError("sidebar page without a subject folder: " + path) return SIDEBAR_ROUTES[parts[1]] return FOLDER_TO_SITE[parts[0]] tests = [ "hungary/hungarian-basic-3/hungarian_basic_conversation_3_1.html", "japan/hiragana-1/hiragana_1_1.html", "sidebar/linux/example_cheat_sheet.html", "sidebar/web-development/example_lesson.html", "web-servers/apache-in-depth/example_chapter.html", ] for t in tests: print(f"{site_for(t):<16} {t}") Output (checked by running it): languages hungary/hungarian-basic-3/hungarian_basic_conversation_3_1.html languages japan/hiragana-1/hiragana_1_1.html systems sidebar/linux/example_cheat_sheet.html webdevelopment sidebar/web-development/example_lesson.html webdevelopment web-servers/apache-in-depth/example_chapter.html Design points ------------- - A KeyError for an unknown folder is deliberate: a path that belongs nowhere should stop the build, not silently land on the wrong site. - Sidebar pages are routed by the subject folder under sidebar/, so a Linux cheat sheet moves with the systems site instead of staying behind. - The same function can be used by the build script, the navigation and the redirect generator, so all three agree about where a page lives. WHY THIS WORKS AS AN ANSWER --------------------------- One function that answers "which site owns this page?" is the single source of truth for everything later in the course: building each site, drawing its navigation and generating redirects for the old URLs. Keeping the mapping in data (the two dictionaries) rather than in if-statements means a change of mind is a one-line edit, not a code change.