Dash㊵(Locationコンポーネント)

Locationコンポーネント

Locationコンポーネントは、アドレスバーの役割を担います。

コールバックと合わせて使用することで、アドレスバーLinkコンポーネントで指定されたパス(URL)に応じたコンテンツ(ページ)を表示することができます。

ローケーションの設定値は次の通りです。

オプション データ型 内容
hash 文字列 URLの#以降の部分
href 文字列 URLの全体
pathname 文字列 URLのパス名
refresh ブール型 ロケーションが更新された場合に、ページを更新するかどうか。
デフォルトはTrue。
search 文字列 URLのサーチ部分

コンポーネントの役割を確認するために、Locationコンポーネントの属性値を表示するアプリケーションを作成します。

[ソースコード]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__) # Dashインスタンスを生成

app.layout = html.Div(
[
dcc.Location(id='dcc_location'),
html.Div(id='location1'),
html.Div(id='location2'),
html.Div(id='location3'),
html.Div(id='location4'),
html.Br(),
dcc.Link('/test', href='/test'),
html.Br(),
dcc.Link('/test?what', href='/test?what'),
html.Br(),
dcc.Link('/test?what#dashhash', href='/test?what#dashhash'),
html.Br(),
dcc.Link('home', href='/')
],
style={'fontSize':30, 'textAlign':'center'}
)

# コールバックの定義
@app.callback(
Output('location1', 'children'),
Output('location2', 'children'),
Output('location3', 'children'),
Output('location4', 'children'),
Input('dcc_location', 'href'),
Input('dcc_location', 'pathname'),
Input('dcc_location', 'search'),
Input('dcc_location', 'hash'),
)
def update_location(url, pathname, search, hash):
return (
'href={}'.format(url),
'pathname={}'.format(pathname),
'search={}'.format(search),
'hash={}'.format(hash)
)

if __name__ == '__main__':
app.run_server(debug=True) # アプリケーションを起動

[ブラウザで表示]

初期画面としては、href属性pathname属性の値が表示されます。

/test?what#dashhashをクリックすると、search属性hash属性が表示されます。

複数ページのアプリケーションを実現するには、LocationコンポーネントLinkコンポーネントコールバックを組み合わせることになります。