手始めに、引数に属性を渡してやると、HTMLタグ文字列を返す関数を書いてみます。
これは、例えば<img>タグであれば、
from html_tag.img_tag import img_tag as img tag = img(src='my_image.jpg', alt='私の画像') print(img.tag())
のように使えるようにするものです。
ディレクトリ構成
パッケージルートディレクトリのtext2htmlの中にhtml_tagディレクトリを作成し、その中に各種HTMLタグを表すクラスを書いていくことにします。
text2html (プロジェクトルートディレクトリ) └── text2html (パッケージルートディレクトリ) ├── sohtml.py └── html_tag └── image.py
Pythonコードを書きます。
(ファイル名) image.py
def img_tag(src, alt=None, title=None): if alt is not None: alt_prop = 'alt="{alt}" '.format(alt=alt) else: alt_prop = '' if title is not None: title_prop = 'title="{title}" '.format(title=title) else: title_prop = '' return '<img src="{src}" {alt_prop}{title_prop}/>'.format( src=src, alt_prop=alt_prop, title_prop=title_prop) # テストコード if __name__ == '__main__': img = img_tag(src="myimage.jpg", alt="-- 私の画像 --", title="私の画像") print(img)
<a>タグも作っておくと便利です。
こんな感じで、関数化したいHTMLタグがある場合は、その都度html_tagディレクトリの中にPythonコードを書いていきます。
パッケージ化
作成したPythonプログラムがパッケージとして使えるようにするために、__init__.pyファイルを作成します。
text2html(パッケージルートディレクトリ)の直下に以下の内容で__init__.pyを作成します。
import os, sys # text2html直下にあるディレクトリをパッケージとして使えるようにする sys.path.insert(0, os.path.dirname(__file__)) # import text2html # の後、 # text2html.html_tagでアクセスできるようにする # これを書かない場合は、 # from text2html import html_tag # のような記述になる from . import html_tag
html_tagの直下に以下の内容で__init__.pyを作成します。
from . import img_tag # ファイルの数だけ同じように記述する
ちゃんとパッケージ化できたか、対話モードPythonで確認します。
>>> import text2html as th >>> img = th.html_tag.img_tag.img_tag(src="myimg.jpg") >>> print(img) <img src="myimg.jpg" />
うまくいったようです。